"""
eric-kraus: An interactive CLI resume, validated by Pydantic, rendered by Rich.

Usage:
    uvx eric-kraus
    pip install eric-kraus && eric-kraus
"""

from __future__ import annotations

import sys

from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.text import Text

from eric_kraus.data import build_eric
from eric_kraus.models import IdealCandidate, Role

console = Console()

# ---------------------------------------------------------------------------
# Rendering helpers
# ---------------------------------------------------------------------------


def render_header(eric: IdealCandidate) -> None:
    """Renders the header box"""
    header = Text()
    # write out strengths
    header.append(" • ".join(s.name.upper() for s in eric.strengths), style="bold")

    # write info basemodel
    header.append(f"\n\n{eric.name.upper()}\n", style="bold bright_white")
    header.append(f"{eric.email}  •  {eric.phone}  •  {eric.location}\n", style="dim")
    header.append(f"\n{eric.years_experience}+ years enterprise sales\n")
    header.append(
        "\nCreates ",
    )
    header.append(
        "pipeline. ",
        style="italic cyan",
    )
    header.append(
        "Builds ",
    )
    header.append(
        "relationships. ",
        style="italic light_salmon3",
    )
    header.append(
        "Closes ",
    )
    header.append(
        "deals.\n",
        style="italic green4",
    )
    header.append(
        "\n\n(...and writes a little code for fun.)",
        style="italic dim navajo_white3",
    )
    console.print(Panel(header, border_style="bright_blue", padding=(1, 2)))


def render_source_code_hint() -> None:
    """Display source code"""
    console.print("\n💡 Fun Fact: This entire resume is a set of Pydantic models!")
    console.print(
        "[dim]   View the source:"
        '\n[cyan]   python3 -c "from eric_kraus.data import build_eric; '
        'print(build_eric().model_dump_json(indent=2))"[/cyan][/dim]'
    )
    console.print()


def render_role(role: Role) -> Panel:
    """Renders the experience box"""
    end_label = role.end.strftime("%b %Y") if role.end else "Present"
    title = f" [bold]{role.company}[/bold]  —  {role.title} "
    subtitle = (
        f" {role.start.strftime('%b %Y')} → {end_label}  ({role.tenure_years} yrs) "
    )

    lines: list[str] = []
    lines.append("")
    if role.largest_deal:
        if role.company == "Google":
            lines.append(
                f"[bold dark_orange3]Epic win:[/bold dark_orange3] {role.largest_deal}\n"
            )
        else:
            lines.append(
                f"[bold green]Largest deal:[/bold green] {role.largest_deal}\n"
            )
    if role.sold_to:
        lines.append(f"[bold]Sold to:[/bold] {', '.join(role.sold_to)}")
    if role.quota_results:
        for qr in role.quota_results:
            emoji = (
                "🚀"
                if qr.attainment_pct >= 100
                else "🔴"  # let's be honest - unreachable code!
            )
            line = f"{emoji}  {qr.year}: {qr.attainment_pct}%"
            if qr.highlight:
                line += f"  ({qr.highlight})"
            lines.append(line)
    for h in role.highlights:
        lines.append(f"  • {h}")

    lines.append("")
    content = "\n".join(lines)
    return Panel(
        content, title=title, subtitle=subtitle, border_style="blue", padding=(0, 1)
    )


def render_experience(eric: IdealCandidate) -> None:
    """Display experience"""
    console.print("\n[bold bright_white]EXPERIENCE[/bold bright_white]")
    console.print("[dim]Keeping it brief![/dim]\n")
    for role in eric.experience:
        console.print(render_role(role))
        console.print()
        console.print()


def render_projects(eric: IdealCandidate) -> None:
    """Display projects"""
    console.print("\n[bold bright_white]TECHNICAL PROJECTS[/bold bright_white]")
    console.print("[dim]What I work on when not closing deals![/dim]\n")

    table = Table(
        show_header=True, header_style="bold bright_blue", border_style="blue"
    )
    table.add_column("Project", style="bold")
    table.add_column("Description")
    table.add_column("Tech", style="cyan")

    for p in eric.technical_projects:
        table.add_row(
            p.name,
            p.description,
            ", ".join(
                f"[orchid]{t}[/orchid]" if t == "Pydantic" else t
                for t in p.technologies
            ),
        )
        table.add_section()
    console.print(table)


def render_why_pydantic(eric: IdealCandidate) -> None:
    """Display 'Why Pydantic'?"""
    console.print()
    console.print(
        "\n[bold][orchid]WHY PYDANTIC?[/orchid]  [white]WHY ERIC?[/white][/bold] \n"
    )
    console.print(
        Panel(
            f"{eric.why_pydantic}",
            border_style="medium_purple2",
            title=" [bold thistle3]The most important question...[/bold thistle3] ",
            padding=(1, 2),
        )
    )


def render_education(eric: IdealCandidate) -> None:
    """Display education"""
    console.print()
    console.print("\n[bold bright_white]EDUCATION & LANGUAGES[/bold bright_white]\n")
    edu = eric.education
    lines = [
        "",
        f"[bold]{edu.degree}[/bold] — {edu.major}",
        f"Minors: {', '.join(edu.minors)}",
        f"School: {edu.school}",
        f"\nLanguages: {', '.join(eric.languages)}",
        "",
    ]
    console.print(Panel("\n".join(lines), border_style="blue", padding=(0, 1)))


def render_contact(eric: IdealCandidate) -> None:
    """Display contact info"""
    console.print()
    console.print("\n[bold bright_white]LET'S CONNECT![/bold bright_white]\n")
    contact = Text()
    contact.append(f"📧  {eric.email}\n")
    contact.append(f"📱  {eric.phone}\n")
    contact.append(f"📍  {eric.location.split(' ')[0]}\n")
    contact.append("\n✅  Status: ")
    contact.append("Validated", style="bold green")
    console.print(Panel(contact, border_style="green", padding=(1, 2)))


# menu
MENU_OPTIONS = {
    "1": ("Overview", render_header),
    "2": ("Experience", render_experience),
    "3": ("Technical Projects", render_projects),
    "4": ("Why Pydantic?", render_why_pydantic),
    "5": ("Education & Languages", render_education),
    "6": ("Contact", render_contact),
    "7": ("Export as JSON", None),  # special case
    "a": ("Show Everything", None),  # special case
    "q": ("Quit", None),
}


def show_menu() -> None:
    """Display menu"""
    console.print("\n[bold bright_blue]─── MENU ───[/bold bright_blue]")
    for key, (label, _) in MENU_OPTIONS.items():
        style = "[dim]" if key == "q" else ""
        style_end = "[/dim]" if key == "q" else ""
        console.print(f"  {style}[bold]{key}[/bold]  {label}{style_end}")
    console.print()


def show_all(eric: IdealCandidate) -> None:
    """Show all sections"""
    render_source_code_hint()
    render_header(eric)
    render_experience(eric)
    render_projects(eric)
    render_why_pydantic(eric)
    render_education(eric)
    render_contact(eric)


def main() -> None:
    """Main entry"""
    eric = build_eric()  # populate all the data models

    console.print()
    console.print(
        "[bold bright_blue]――――――――――――――――――――――――――――――――――――――――――――――――――[/bold bright_blue]"
    )
    console.print(
        "[bold bright_white]  eric-kraus[/bold bright_white]  [dim]- a resume, validated by Pydantic![/dim]"
    )
    console.print(
        "[bold bright_blue]――――――――――――――――――――――――――――――――――――――――――――――――――[/bold bright_blue]"
    )

    # show the info section
    render_source_code_hint()

    # show everything, non-interactive [e.g. --all]
    if not sys.stdin.isatty() or "--all" in sys.argv:
        render_header(eric)
        render_experience(eric)
        render_projects(eric)
        render_why_pydantic(eric)
        render_education(eric)
        render_contact(eric)
        return

    while True:
        show_menu()
        exit_message = (
            "\n[dim]Thanks for reading. Excited for the opportunity to talk more![/dim]"
        )
        try:
            choice = (
                console.input("[bold bright_blue]→ [/bold bright_blue]").strip().lower()
            )
        except (KeyboardInterrupt, EOFError):
            console.print(exit_message)
            console.print()
            break

        if choice == "q":  # quit
            console.print(exit_message)
            console.print()
            break
        elif choice == "a":  # all
            show_all(eric)
        elif choice == "7":  # export the json
            json_out = eric.model_dump_json(indent=2)
            console.print(f"\n[cyan]{json_out}[/cyan]")
            render_source_code_hint()
        elif choice in MENU_OPTIONS:
            _, fn = MENU_OPTIONS[choice]
            if fn:
                fn(eric)
        else:
            console.print("[red]Invalid choice. Try again.[/red]")


if __name__ == "__main__":
    main()
