import json, re, urllib.request, urllib.error, base64, os
os.chdir('/home/mantapman/.hermes/profiles/atun/workspace/artikel_seo')

def parse_article(filepath):
    with open(filepath, 'r') as f:
        text = f.read()
    
    lines = text.split('\n')
    seo_title = lines[0].replace('# ', '').strip()
    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()
    
    for i, line in enumerate(lines):
        if line.strip() == '## Tags':
            for j in range(i+1, min(i+3, len(lines))):
                maybe = lines[j].strip()
                if maybe and not maybe.startswith('#'):
                    tags_list = [t.strip() for t in maybe.split(',') if t.strip()]
                    break
            break
    
    # Body
    body_lines = []
    in_body = False
    in_wa = False
    in_tags = False
    for line in lines:
        if line.startswith('[H1]'):
            in_body = True
            in_wa = False
            in_tags = False
        if in_body and line.strip() == '[WA Button]':
            in_wa = True
        if in_body and line.strip() == '## Tags':
            in_tags = True
        if in_body and not in_wa and not in_tags:
            body_lines.append(line)
    
    body_text = '\n'.join(body_lines)
    
    # Convert 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 Gutenberg blocks
    paragraphs = body_text.split('\n\n')
    html = ''
    for p in paragraphs:
        p = p.strip()
        if not p:
            continue
        if p.startswith('<h1>') or p.startswith('<h2>') or p.startswith('<h3>'):
            html += f'<!-- wp:heading -->{p}<!-- /wp:heading -->\n'
        else:
            inner = ''.join(p.split('\n'))
            html += f'<!-- wp:paragraph --><p>{inner}</p><!-- /wp:paragraph -->\n'
    
    # Add WA button
    if wa_button and not wa_button.startswith('(Silakan'):
        html += f'<!-- wp:buttons --><div class="wp-block-buttons"><!-- wp:button --><div class="wp-block-button"><a class="wp-block-button__link" href="{wa_button}">Konsultasi Gratis via WhatsApp</a></div><!-- /wp:button --></div><!-- /wp:buttons -->\n'
    
    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,
        'html': html,
        'word_count': word_count
    }

def get_or_create_tags(domain, app_pw, tag_names):
    auth = base64.b64encode(f"bambangbot:{app_pw}".encode()).decode()
    base = f"https://{domain}/wp-json/wp/v2/tags"
    existing = {}
    
    try:
        req = urllib.request.Request(f"{base}?per_page=100")
        req.add_header('Authorization', f'Basic {auth}')
        req.add_header('User-Agent', 'Mozilla/5.0')
        with urllib.request.urlopen(req, timeout=15) as r:
            for t in json.loads(r.read()):
                existing[t['slug']] = t['id']
    except:
        pass
    
    ids = []
    for name in tag_names:
        slug = name.lower().replace(' ', '-').replace('.','').replace(',','')
        if slug in existing:
            ids.append(existing[slug])
        else:
            try:
                data = json.dumps({'name': name, 'slug': slug}).encode()
                req = urllib.request.Request(base, data=data,
                    headers={'Authorization': f'Basic {auth}', 'Content-Type': 'application/json', 'User-Agent': 'Mozilla/5.0'})
                with urllib.request.urlopen(req, timeout=15) as r:
                    t = json.loads(r.read())
                    ids.append(t['id'])
                    existing[slug] = t['id']
            except Exception as e:
                print(f"        Tag create fail for '{name}': {e}")
    return ids

def upload(domain, app_pw, article):
    auth = base64.b64encode(f"bambangbot:{app_pw}".encode()).decode()
    
    # Get tags
    tag_ids = get_or_create_tags(domain, app_pw, article['tags'])
    
    post_data = {
        'title': article['seo_title'],
        'content': article['html'],
        'slug': article['slug'],
        'status': 'publish',
        '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']
    
    if not post_data['meta']:
        del post_data['meta']
    
    json_data = json.dumps(post_data).encode()
    
    print(f"    📤 {article['slug']} ({article['word_count']} kata) | tags: {', '.join(article['tags'])}")
    
    req = urllib.request.Request(
        f"https://{domain}/wp-json/wp/v2/posts",
        data=json_data,
        headers={
            'Authorization': f'Basic {auth}',
            'Content-Type': 'application/json',
            'User-Agent': 'Mozilla/5.0'
        }
    )
    
    try:
        with urllib.request.urlopen(req, timeout=30) as resp:
            result = json.loads(resp.read())
            print(f"    ✅ Post {result['id']} → {result['link']}")
            return result['id']
    except urllib.error.HTTPError as e:
        body = e.read().decode()[:300]
        print(f"    ❌ {e.code}: {body}")
        return None

# ============ STUDIOSOFT (retry) ============
print("\n" + "="*60)
print("📍 STUDIOSOFT (studiosoft.id) — RETRY")
print("="*60)

# Try without meta first - simple post
for fname in ['studiosoft_seo-untuk-umkm.txt', 'studiosoft_pentingnya-website-untuk-bisnis.txt', 'studiosoft_ai-untuk-marketing.txt']:
    article = parse_article(fname)
    # Clean HTML - remove heading tags, wrap everything in paragraphs
    article['html'] = article['html'].replace('<!-- wp:heading --><h1>', '<!-- wp:paragraph --><p><strong>')
    article['html'] = article['html'].replace('</h1><!-- /wp:heading -->', '</strong></p><!-- /wp:paragraph -->')
    article['html'] = article['html'].replace('<!-- wp:heading --><h2>', '<!-- wp:paragraph --><p><strong>')
    article['html'] = article['html'].replace('</h2><!-- /wp:heading -->', '</strong></p><!-- /wp:paragraph -->')
    article['html'] = article['html'].replace('<!-- wp:heading --><h3>', '<!-- wp:paragraph --><p><strong>')
    article['html'] = article['html'].replace('</h3><!-- /wp:heading -->', '</strong></p><!-- /wp:paragraph -->')
    
    upload('studiosoft.id', 'q26r RePo BVy6 pwU2 F3z7 ouyl', article)

# ============ TSLaw ============
print("\n" + "="*60)
print("📍 TSLAW (tslaw.id)")
print("="*60)

for fname in ['ttalaw_panduan-mendirikan-pt-untuk-umkm.txt', 'ttalaw_kontrak-bisnis-yang-aman.txt', 'ttalaw_cara-daftar-merek-dagang.txt']:
    article = parse_article(fname)
    upload('tslaw.id', 'EFKm EYGx VQCP Y9go ncPr uM2Y', article)

print("\n✅ Done!")
