import json, re, sys, urllib.request, urllib.error, base64

def parse_article(filepath):
    with open(filepath, 'r') as f:
        text = f.read()
    
    lines = text.split('\n')
    seo_title = lines[0].replace('# ', '').strip() if lines[0].startswith('# ') else ''
    meta_desc = lines[1].replace('# ', '').strip() if len(lines) > 1 and lines[1].startswith('# ') else ''
    keyphrase = ''
    slug = ''
    wa_button = ''
    tags_list = []
    
    for i, line in enumerate(lines):
        if line.startswith('# Keyphrase:'):
            keyphrase = line.replace('# Keyphrase:', '').strip()
        elif line.startswith('# Slug:'):
            slug = line.replace('# Slug:', '').strip()
        elif line.startswith('# WA Button:'):
            wa_button = line.replace('# WA Button:', '').strip()
    
    # Extract tags
    for i, line in enumerate(lines):
        if line.strip() == '## Tags':
            for j in range(i+1, min(i+3, len(lines))):
                maybe_tags = lines[j].strip()
                if maybe_tags and not maybe_tags.startswith('#'):
                    tags_list = [t.strip() for t in maybe_tags.split(',') if t.strip()]
                    break
            break
    
    # Find body start
    body_start = 0
    for i, line in enumerate(lines):
        if line.startswith('[H1]'):
            body_start = i
            break
    
    # Get body - cut at WA Button or Tags section
    body_lines = lines[body_start:]
    body_text = '\n'.join(body_lines)
    
    if '[WA Button]' in body_text:
        body_text = body_text.split('[WA Button]')[0].strip()
    if '## Tags' in body_text:
        body_text = body_text.split('## Tags')[0].strip()
    
    # Process markdown to HTML
    body_text = re.sub(r'^\[H1\] (.+)$', r'<h1>\1</h1>', body_text, flags=re.MULTILINE)
    body_text = re.sub(r'^## (.+)$', r'<h2>\1</h2>', body_text, flags=re.MULTILINE)
    body_text = re.sub(r'^### (.+)$', r'<h3>\1</h3>', body_text, flags=re.MULTILINE)
    
    # Build paragraphs
    paragraphs = []
    current_para = []
    
    for line in body_text.split('\n'):
        line = line.strip()
        if not line:
            if current_para:
                paragraphs.append(('p', ' '.join(current_para)))
                current_para = []
        elif line.startswith('<h1>') or line.startswith('<h2>') or line.startswith('<h3>'):
            if current_para:
                paragraphs.append(('p', ' '.join(current_para)))
                current_para = []
            tag = line[1:3].replace('>', '')
            content = line[4:-5].strip()
            paragraphs.append((tag, content))
        elif line.startswith('### '):
            if current_para:
                paragraphs.append(('p', ' '.join(current_para)))
                current_para = []
            paragraphs.append(('h3', line[4:]))
        elif line.startswith('## '):
            if current_para:
                paragraphs.append(('p', ' '.join(current_para)))
                current_para = []
            paragraphs.append(('h2', line[3:]))
        elif line.startswith('# '):
            if current_para:
                paragraphs.append(('p', ' '.join(current_para)))
                current_para = []
            paragraphs.append(('h1', line[2:]))
        else:
            current_para.append(line)
    
    if current_para:
        paragraphs.append(('p', ' '.join(current_para)))
    
    # Add WA button if available
    if wa_button and not wa_button.startswith('(Silakan') and wa_button != '(Silakan hubungi...':
        wa_text = "Konsultasi Gratis via WhatsApp"
        if 'DAS' in filepath or 'das' in filepath:
            wa_text = "Konsultasi Engine via WhatsApp"
        paragraphs.append(('wa_button', f'<a href="{wa_button}">{wa_text}</a>'))
    
    # Build HTML
    html_blocks = []
    for tag, content in paragraphs:
        if tag == 'wa_button':
            html_blocks.append(f'<div class="wp-block-buttons"><div class="wp-block-button"><a class="wp-block-button__link" href="#">{content}</a></div></div>')
        else:
            html_blocks.append(f'<!-- wp:paragraph --><p>{content}</p><!-- /wp:paragraph -->')
    
    full_html = '\n'.join(html_blocks)
    word_count = len(re.sub(r'<[^>]+>', '', body_text).split())
    
    return {
        'seo_title': seo_title,
        'meta_desc': meta_desc,
        'keyphrase': keyphrase,
        'slug': slug,
        'tags': tags_list,
        'full_html': full_html,
        'word_count': word_count
    }

def upload_post(domain, app_pw, article, wa_link=None):
    auth = base64.b64encode(f"bambangbot:{app_pw}".encode()).decode()
    url = f"https://{domain}/wp-json/wp/v2/posts"
    
    # Get categories
    default_cat = None
    try:
        req = urllib.request.Request(f"https://{domain}/wp-json/wp/v2/categories?per_page=50")
        req.add_header('Authorization', f'Basic {auth}')
        with urllib.request.urlopen(req, timeout=15) as resp:
            cats = json.loads(resp.read())
            if cats:
                default_cat = cats[0]['id']
    except Exception as e:
        print(f"   ⚠️ Cat fetch failed: {e}")
    
    # Get existing tags
    existing_tags = {}
    try:
        req = urllib.request.Request(f"https://{domain}/wp-json/wp/v2/tags?per_page=100")
        req.add_header('Authorization', f'Basic {auth}')
        with urllib.request.urlopen(req, timeout=15) as resp:
            for t in json.loads(resp.read()):
                existing_tags[t['slug']] = t['id']
    except:
        pass
    
    # Create tags
    tag_ids = []
    for tag_name in article['tags']:
        tag_slug = tag_name.lower().replace(' ', '-').replace('.','').replace(',','')
        if tag_slug in existing_tags:
            tag_ids.append(existing_tags[tag_slug])
        else:
            try:
                create_data = json.dumps({'name': tag_name, 'slug': tag_slug}).encode()
                req = urllib.request.Request(
                    f"https://{domain}/wp-json/wp/v2/tags",
                    data=create_data,
                    headers={'Authorization': f'Basic {auth}', 'Content-Type': 'application/json'}
                )
                with urllib.request.urlopen(req, timeout=15) as cresp:
                    new_tag = json.loads(cresp.read())
                    tag_ids.append(new_tag['id'])
                    existing_tags[tag_slug] = new_tag['id']
            except:
                pass
    
    # Build post
    post_data = {
        'title': article['seo_title'],
        'content': article['full_html'],
        'slug': article['slug'],
        'status': 'publish',
        'categories': [default_cat] if default_cat else [],
        'tags': tag_ids,
        'meta': {}
    }
    
    if article['meta_desc']:
        post_data['meta']['_yoast_wpseo_metadesc'] = article['meta_desc']
    if article['keyphrase']:
        post_data['meta']['_yoast_wpseo_focuskw'] = article['keyphrase']
    if article['seo_title']:
        post_data['meta']['_yoast_wpseo_title'] = article['seo_title']
    
    # Remove empty meta
    if not post_data['meta']:
        del post_data['meta']
    
    json_data = json.dumps(post_data).encode()
    
    print(f"   📤 Uploading: {article['slug']}")
    print(f"     Title: {article['seo_title'][:60]}...")
    print(f"     Words: {article['word_count']}")
    print(f"     Tags: {', '.join(article['tags'])}")
    print(f"     HTML: {len(article['full_html'])} chars")
    
    req = urllib.request.Request(
        url, data=json_data,
        headers={'Authorization': f'Basic {auth}', 'Content-Type': 'application/json'}
    )
    
    try:
        with urllib.request.urlopen(req, timeout=30) as resp:
            result = json.loads(resp.read())
            print(f"   ✅ Post ID: {result['id']} | URL: {result['link']}")
            return result['id']
    except urllib.error.HTTPError as e:
        body = e.read().decode()[:300]
        print(f"   ❌ {e.code}: {body}")
        return None
    except Exception as e:
        print(f"   ❌ {e}")
        return None

if __name__ == '__main__':
    import os
    os.chdir('/home/mantapman/.hermes/profiles/atun/workspace/artikel_seo')
    
    files_map = {
        'studiosoft.id': {
            'app_pw': 'q26r RePo BVy6 pwU2 F3z7 ouyl',
            'files': ['studiosoft_seo-untuk-umkm.txt', 'studiosoft_pentingnya-website-untuk-bisnis.txt', 'studiosoft_ai-untuk-marketing.txt']
        },
        'www.apotekpamekasan.com': {
            'app_pw': 'Rab8 qmxV gJ1k yDY3 9ske utCz',
            'files': ['apotek_cara-mengatasi-demam-anak.txt', 'apotek_vitamin-untuk-daya-tahan-tubuh.txt', 'apotek_bahaya-antibiotik-tanpa-resep-dokter.txt']
        },
        'ttalawfirm.id': {
            'app_pw': 'EFKm EYGx VQCP Y9go ncPr uM2Y',
            'files': ['ttalaw_panduan-mendirikan-pt-untuk-umkm.txt', 'ttalaw_kontrak-bisnis-yang-aman.txt', 'ttalaw_cara-daftar-merek-dagang.txt']
        },
        'dasindonesia.com': {
            'app_pw': 'u3a1 G2pQ 3SWY f0zI OlGP YAjU',
            'files': ['das_kapan-mobil-perlu-engine-overhaul.txt', 'das_penyebab-mesin-mobil-overheat.txt', 'das_cara-merawat-mesin-mobil-agar-awet.txt']
        }
    }
    
    for domain, config in files_map.items():
        print(f"\n{'='*60}")
        print(f"📍 {domain}")
        print('='*60)
        
        for fname in config['files']:
            if not os.path.exists(fname):
                print(f"   ⚠️ File not found: {fname}")
                continue
            article = parse_article(fname)
            upload_post(domain, config['app_pw'], article)
    
    print(f"\n{'='*60}")
    print("✅ SELESAI!")
