#!/usr/bin/env python3
"""
Export Claude Code conversation from JSONL to MDX format and optionally deploy to Vercel.

This is a convenience wrapper that combines convert-claude-chat.py and deploy-to-vercel.py.

Usage:
    python export-claude-chat.py <jsonl-file> [--output <output-file>] [--title <title>] [--deploy]

    # Export latest session
    python export-claude-chat.py $(ls -t ~/.claude/projects/*/*.jsonl | head -n 1)

    # Export with custom title and output
    python export-claude-chat.py session.jsonl --title "My Conversation" --output my-convo.mdx

    # Export and deploy to Vercel
    python export-claude-chat.py session.jsonl --title "My Conversation" --output my-convo.mdx --deploy
"""

import argparse
import subprocess
import sys
from pathlib import Path


def main():
    parser = argparse.ArgumentParser(
        description="Export Claude Code conversation and optionally deploy to Vercel.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # Export latest session
  python export-claude-chat.py $(ls -t ~/.claude/projects/*/*.jsonl | head -n 1)

  # Export with custom title
  python export-claude-chat.py session.jsonl --title "Building a Wiki Feature"

  # Export to specific output file
  python export-claude-chat.py session.jsonl --output ../src/content/prompts/my-chat.mdx

  # Export and deploy to Vercel
  python export-claude-chat.py session.jsonl --title "My Chat" --output my-chat.mdx --deploy
        """,
    )

    parser.add_argument(
        "jsonl_file", type=Path, help="Path to Claude Code JSONL session file"
    )
    parser.add_argument(
        "--output", "-o", type=Path, help="Output MDX file path (default: stdout)"
    )
    parser.add_argument(
        "--title",
        "-t",
        type=str,
        help="Title for the conversation (default: auto-generated)",
    )
    parser.add_argument(
        "--deploy",
        "-d",
        action="store_true",
        help="Deploy to Vercel after export and return preview URL",
    )

    args = parser.parse_args()

    # Get script directory
    script_dir = Path(__file__).parent.resolve()
    convert_script = script_dir / "convert-claude-chat.py"
    deploy_script = script_dir / "deploy-to-vercel.py"

    # Validate scripts exist
    if not convert_script.exists():
        print(f"Error: convert-claude-chat.py not found at {convert_script}", file=sys.stderr)
        sys.exit(1)

    if args.deploy and not deploy_script.exists():
        print(f"Error: deploy-to-vercel.py not found at {deploy_script}", file=sys.stderr)
        sys.exit(1)

    # Step 1: Run convert script
    print("📝 Converting conversation to MDX...")
    convert_cmd = ["python3", str(convert_script), str(args.jsonl_file)]

    if args.output:
        convert_cmd.extend(["--output", str(args.output)])
    if args.title:
        convert_cmd.extend(["--title", args.title])

    result = subprocess.run(convert_cmd, capture_output=True, text=True)

    if result.returncode != 0:
        print("❌ Conversion failed:", file=sys.stderr)
        print(result.stderr, file=sys.stderr)
        sys.exit(1)

    print(result.stdout)

    # Step 2: Deploy if requested
    if args.deploy:
        if not args.output:
            print("Error: --deploy requires --output to be specified", file=sys.stderr)
            sys.exit(1)

        print("\n" + "=" * 50)
        deploy_cmd = ["python3", str(deploy_script), "--prompt-file", str(args.output)]

        result = subprocess.run(deploy_cmd, capture_output=True, text=True)

        print(result.stdout)
        if result.stderr:
            print(result.stderr, file=sys.stderr)

        sys.exit(result.returncode)


if __name__ == "__main__":
    main()
