"""End-to-end test: generate draft and publish to Zhihu from command line.

Usage:
    python scripts/zhihu_e2e_test.py \
        --url "https://www.zhihu.com/question/2012492934491108892" \
        --outline "1. 明确表示就是智商税..."
"""

import sys
import re
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from health.utils.env_loader import load_env_with_extras
load_env_with_extras()

import click
from health.utils.logging_config import setup_logger
logger = setup_logger("zhihu_e2e_test")


@click.command()
@click.option("--url", required=True, help="Zhihu question URL")
@click.option("--outline", default="", help="Answer outline/logic")
@click.option("--dry-run", is_flag=True, default=False, help="Generate draft only, skip publish")
def main(url: str, outline: str, dry_run: bool) -> None:
    """Generate and publish a Zhihu answer end-to-end."""
    from health import config
    from slack_bot.obsidian.embeddings import get_embedding_provider
    from slack_bot.obsidian.vector_store import ChromaVectorStore
    from slack_bot.obsidian.indexer import ObsidianIndexer
    from slack_bot.zhihu.zhihu_hunter import ZhihuHunter, ZhihuQuestion
    from slack_bot.zhihu.zhihu_playwright_engine import ZhihuPlaywrightEngine
    import os

    # Clean URL
    url = re.sub(r'[>\'")\].,;]+$', '', url).split("?")[0].split("#")[0].rstrip("/")
    click.echo(f"URL: {url}")

    vault_path = Path(os.environ["OBSIDIAN_VAULT_PATH"])

    # Init components
    click.echo("⏳ Initialising vector store and indexer...")
    vector_store = ChromaVectorStore(embedding_provider=get_embedding_provider())
    indexer = ObsidianIndexer(str(vault_path))
    indexer.scan_vault()
    hunter = ZhihuHunter(vault_path=vault_path, vector_store=vector_store, indexer=indexer)

    # Fetch question title
    click.echo("⏳ Fetching question title...")
    questions = hunter.hunt_direct_url(url)
    question = questions[0]
    if outline:
        question.outline = outline
    click.echo(f"Question: {question.title}")

    # Generate draft
    click.echo("⏳ Generating draft answer...")
    draft = hunter.draft_answer(question)
    click.echo("\n" + "=" * 60)
    click.echo(draft.content)
    click.echo("=" * 60 + "\n")
    click.echo(f"Length: {len(draft.content)} chars")

    # Save to vault
    import re as _re
    from datetime import date
    vault_zhihu_dir = vault_path / "zhihu"
    vault_zhihu_dir.mkdir(parents=True, exist_ok=True)
    date_str = date.today().strftime("%Y-%m-%d")
    slug = _re.sub(r'[^\w\u4e00-\u9fff]+', '-', question.title)[:40].strip('-')
    vault_file = vault_zhihu_dir / f"{date_str}-{slug}.md"
    vault_file.write_text(
        f"---\ntitle: \"{question.title}\"\nurl: {url}\ndate: {date_str}\n"
        f"status: draft\ntags: [zhihu]\n---\n\n# {question.title}\n\n{draft.content}\n",
        encoding="utf-8",
    )
    click.echo(f"✅ Draft saved to vault: {vault_file}")

    if dry_run:
        click.echo("--dry-run: skipping publish.")
        return

    # Publish
    slack_token = os.environ.get("OBSIDIAN_SLACK_BOT_TOKEN", "")
    notify_channel = os.environ.get("ZHIHU_NOTIFY_CHANNEL", "")
    from slack_sdk import WebClient
    slack_client = WebClient(token=slack_token)
    engine = ZhihuPlaywrightEngine(slack_client=slack_client, notify_channel=notify_channel)

    click.echo("⏳ Checking Zhihu session...")
    if not engine.ensure_logged_in():
        click.echo("❌ Zhihu login failed. Check QR code in Slack.")
        sys.exit(1)

    click.echo("⏳ Publishing answer...")
    try:
        answer_url = engine.publish_answer(question_url=url, answer_text=draft.content)
        click.echo(f"✅ Published: {answer_url}")

        # Update vault file status
        content = vault_file.read_text(encoding="utf-8")
        content = content.replace("status: draft", f"status: published\nanswer_url: {answer_url}", 1)
        vault_file.write_text(content, encoding="utf-8")
        click.echo(f"✅ Vault file updated to published.")
    except Exception as e:
        click.echo(f"❌ Publish failed: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()
