"""CLI entry point for cv4offer."""

import argparse
import json
import re
import sys
from pathlib import Path

from . import __version__


def cmd_generate(args):
    """Generate a tailored CV from master CV + job posting."""
    from .checker import check_cv
    from .tailor import generate_cv

    posting_path = Path(args.posting)
    master_path = Path(args.master)

    if not posting_path.exists():
        print(f"Error: posting file not found: {posting_path}", file=sys.stderr)
        sys.exit(1)
    if not master_path.exists():
        print(f"Error: master CV not found: {master_path}", file=sys.stderr)
        sys.exit(1)

    from .parser import parse_master
    parsed = parse_master(master_path)
    print(f"Parsed master CV: {len(parsed['skills'])} skills, "
          f"{len(parsed['bullets'])} bullets, "
          f"{len(parsed['frozen_sections'])} frozen sections")

    print("Analyzing job posting and selecting optimal content...")
    result = generate_cv(
        posting_path=posting_path,
        master_path=master_path,
        output_path=args.output,
        api_key=args.api_key,
        compile_pdf=not args.no_compile,
    )

    selection = result["selection"]
    analysis = selection.get("analysis", {})

    print(f"\nJob analysis:")
    print(f"  Company: {analysis.get('company_name', '?')}")
    print(f"  Position: {analysis.get('position_title', '?')}")
    print(f"  Industry: {analysis.get('industry', '?')}")
    print(f"  ATS keywords: {', '.join(analysis.get('ats_keywords', []))}")

    print(f"\nSelected {len(selection.get('selected_skills', []))} skills")
    print(f"Achievement: {selection.get('selected_achievement', '?')}")

    # Save selection JSON alongside tex
    tex_path = Path(result["tex_path"])
    selection_path = tex_path.with_suffix(".selection.json")
    selection_path.write_text(
        json.dumps(selection, indent=2, ensure_ascii=False), encoding="utf-8"
    )

    # ATS coverage report
    coverage = selection.get("ats_coverage", {})
    if coverage:
        print("\nATS Coverage:")
        for keyword, location in coverage.items():
            mark = "✓" if location else "✗"
            print(f"  [{mark}] {keyword} -> {location}")

    print(f"\nTeX: {result['tex_path']}")
    if "pdf_path" in result:
        print(f"PDF: {result['pdf_path']}")

        # Auto-check quality
        check_result = check_cv(result["tex_path"])
        if "error" not in check_result:
            s = check_result["summary"]
            print(f"\nQuality: {s['critical']} critical, {s['warning']} warnings, {s['info']} info")
            print(f"Pages: {check_result['pages']}, fill: {check_result['page_fill']}")
            if s["critical"] > 0 or s["warning"] > 0:
                for issue in check_result["issues"]:
                    if issue["severity"] in ("CRITICAL", "WARNING"):
                        print(f"  [{issue['severity']}] {issue['type']}: {issue.get('text', '')}")

    print("\nDone.")


def cmd_check(args):
    """Run visual quality check on a compiled CV."""
    from .checker import check_cv

    result = check_cv(
        args.tex_file,
        expected_pages=args.pages,
    )

    if "error" in result:
        print(f"Error: {result['error']}", file=sys.stderr)
        sys.exit(3)

    print(json.dumps(result, indent=2, ensure_ascii=False))

    if result["summary"]["critical"] > 0:
        sys.exit(2)
    elif result["summary"]["warning"] > 0:
        sys.exit(1)


def cmd_parse(args):
    """Parse a master CV and show available content pools."""
    from .parser import get_bullet_variants, get_skill_groups, parse_master

    parsed = parse_master(args.master)

    print(f"Skills: {len(parsed['skills'])}")
    groups = get_skill_groups(parsed)
    for group, skills in groups.items():
        print(f"  {group}: {len(skills)} items")
        if args.verbose:
            for sid, content in skills:
                print(f"    {sid}: {content}")

    print(f"\nBullets: {len(parsed['bullets'])}")
    companies = set()
    for tag_id in parsed["bullets"]:
        m = re.match(r"^([a-zA-Z]+)_", tag_id)
        if m:
            companies.add(m.group(1))
    for company in sorted(companies):
        variants = get_bullet_variants(parsed, company)
        total = sum(len(v) for v in variants.values())
        print(f"  {company}: {len(variants)} bullets, {total} variants")

    print(f"\nAchievements: {len(parsed['achievements'])}")
    for aid, content in parsed["achievements"].items():
        print(f"  {aid}: {content[:60]}...")

    print(f"\nSummaries: {len(parsed['summaries'])}")
    print(f"Frozen sections: {', '.join(parsed['frozen_sections'].keys())}")
    print(f"Placeholders: {', '.join(parsed['placeholders'].keys())}")


def main():
    parser = argparse.ArgumentParser(
        prog="cv4offer",
        description="AI-powered CV tailor. Generates job-specific CVs from your master CV.",
    )
    parser.add_argument("--version", action="version", version=f"cv4offer {__version__}")

    sub = parser.add_subparsers(dest="command", help="Available commands")

    # generate
    gen = sub.add_parser("generate", help="Generate a tailored CV for a job posting")
    gen.add_argument("posting", help="Path to job posting file (.md or .txt)")
    gen.add_argument("--master", "-m", required=True, help="Path to master CV (.tex)")
    gen.add_argument("--output", "-o", help="Output .tex path (default: cv_<company>.tex)")
    gen.add_argument("--api-key", help="Anthropic API key (or set ANTHROPIC_API_KEY)")
    gen.add_argument("--no-compile", action="store_true", help="Skip PDF compilation")
    gen.set_defaults(func=cmd_generate)

    # check
    chk = sub.add_parser("check", help="Run visual quality check on compiled CV")
    chk.add_argument("tex_file", help="Path to .tex file (PDF must exist)")
    chk.add_argument("--pages", type=int, default=2, help="Expected page count (default: 2)")
    chk.set_defaults(func=cmd_check)

    # parse
    prs = sub.add_parser("parse", help="Parse master CV and show content pools")
    prs.add_argument("master", help="Path to master CV (.tex)")
    prs.add_argument("--verbose", "-v", action="store_true", help="Show all items")
    prs.set_defaults(func=cmd_parse)

    args = parser.parse_args()
    if not args.command:
        parser.print_help()
        sys.exit(1)

    args.func(args)


if __name__ == "__main__":
    main()
