from __future__ import annotations

from dataclasses import asdict
from typing import Iterable, Optional

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

console = Console()


def print_banner() -> None:
    banner = r"""
       _       _     _                                         
      | |     | |   | |                                        
      | | ___ | |__ | |__   ___ _ __ _ __ ___   __ _ _ __      
  _   | |/ _ \ | '_ \| '_ \ / _ \ '__| '_ ` _ \ / _` | '_ \     
 | |__| | (_) | |_) | |_) |  __/ |  | | | | | | (_| | | | |    
  \____/ \___/|_.__/|_.__/ \___|_|  |_| |_| |_|\__,_|_| |_|    
    """
    # Use raw print with bold cyan ANSI to prevent line wrapping by rich.Console
    print(f"\033[1;36m{banner}\033[0m")


def header(title: str) -> None:
    console.print(Panel.fit(Text(title, style="bold cyan"), border_style="cyan"))


def section(title: str) -> None:
    console.print(Panel.fit(Text(title, style="bold"), border_style="blue"))


def show_warnings(warnings: Iterable[str]) -> None:
    warnings = list(warnings)
    if not warnings:
        return
    table = Table.grid(padding=(0, 1))
    for w in warnings:
        table.add_row(Text(f"! {w}", style="yellow"))
    console.print(table)


def job_summary_table(job: object) -> None:
    # Expects JobDescription-like object with common attributes.
    table = Table(show_header=False, box=box.ROUNDED, border_style="bold cyan")
    table.add_row(Text("Title", style="bold"), Text(getattr(job, "title", "") or ""))
    table.add_row(Text("Company", style="bold"), Text(getattr(job, "company", "") or ""))
    table.add_row(Text("Location", style="bold"), Text(getattr(job, "location", "") or ""))
    url: Optional[str] = getattr(job, "url", None)
    if url:
        table.add_row(Text("URL", style="bold"), Text(url))
    console.print(table)


def render_tailored_resume(tailored_resume: object) -> None:
    summary = getattr(tailored_resume, "summary", "") or ""
    highlighted = getattr(tailored_resume, "highlighted_skills", []) or []
    bullets = getattr(tailored_resume, "bullet_points", []) or []
    
    content = ""
    if summary:
        content += f"{summary}\n\n"
    if highlighted:
        content += f"**Highlighted skills:** {', '.join(highlighted)}\n\n"
    if bullets:
        content += "**Suggested bullets:**\n"
        for b in bullets:
            content += f"- {b}\n"

    console.print(Panel(Markdown(content.strip()), title="[bold blue]Tailored Resume[/]", border_style="blue", box=box.ROUNDED))
    show_warnings(getattr(tailored_resume, "warnings", []) or [])


def render_cover_letter(tailored_cover: object) -> None:
    intro = getattr(tailored_cover, "intro", "") or ""
    body = getattr(tailored_cover, "body", "") or ""
    closing = getattr(tailored_cover, "closing", "") or ""

    content = f"{intro}\n\n{body}\n\n{closing}"
    
    console.print(Panel(Markdown(content.strip()), title="[bold blue]Tailored Cover Letter[/]", border_style="blue", box=box.ROUNDED))
    show_warnings(getattr(tailored_cover, "warnings", []) or [])


def render_portfolio_suggestions(suggestions: Iterable[object]) -> None:
    section("Portfolio Suggestions")
    table = Table(show_header=True, header_style="bold magenta", box=box.ROUNDED, border_style="magenta")
    table.add_column("Priority")
    table.add_column("Title")
    table.add_column("Description")

    for s in suggestions:
        priority = str(getattr(s, "priority", "") or "").upper()
        title = str(getattr(s, "title", "") or "")
        description = str(getattr(s, "description", "") or "")
        table.add_row(priority, title, description)
    console.print(table)


def render_interview_questions(turns: Iterable[object]) -> None:
    section("Mock Interview")
    for idx, turn in enumerate(turns, start=1):
        q = getattr(turn, "question", turn)
        category = getattr(q, "category", "")
        question = getattr(q, "question", "")
        console.print(Text(f"Q{idx} ({category}): {question}", style="bold"))
        focus_areas = getattr(q, "focus_areas", []) or []
        if focus_areas:
            console.print(Text(f"  Focus: {', '.join(focus_areas)}", style="dim"))
        console.print()

