"""Report generation: HTML catalog, Markdown, terminal stats."""

import sys

from .config import PROJECT_ROOT
from .db import get_db, print_stats


def format_duration(seconds):
    """Format seconds as 'Xm XXs'."""
    if seconds is None:
        return "?"
    m = int(seconds // 60)
    s = int(seconds % 60)
    return f"{m}m {s:02d}s"


def generate_html():
    """Generate a standalone catalog.html file."""
    conn = get_db()

    videos = conn.execute("""
        SELECT v.*, COUNT(DISTINCT f.id) as frame_count, COUNT(DISTINCT fc.id) as face_count
        FROM videos v
        LEFT JOIN frames f ON v.id = f.video_id
        LEFT JOIN faces fc ON v.id = fc.video_id
        GROUP BY v.id
        ORDER BY v.number
    """).fetchall()

    people = conn.execute("""
        SELECT p.*,
               COUNT(DISTINCT vp.video_id) as video_count,
               COUNT(DISTINCT f.id) as face_count
        FROM people p
        LEFT JOIN video_people vp ON p.id = vp.person_id
        LEFT JOIN faces f ON p.id = f.person_id
        GROUP BY p.id
        ORDER BY p.name
    """).fetchall()

    places = conn.execute("""
        SELECT pl.*, COUNT(DISTINCT vpl.video_id) as video_count
        FROM places pl
        LEFT JOIN video_places vpl ON pl.id = vpl.place_id
        GROUP BY pl.id
        ORDER BY pl.region, pl.name
    """).fetchall()

    total_duration = sum(v["duration_seconds"] or 0 for v in videos)
    hours = int(total_duration // 3600)
    total_frames = sum(v["frame_count"] for v in videos)
    total_faces = sum(v["face_count"] for v in videos)

    # Build video cards
    video_cards = ""
    for v in videos:
        frames = conn.execute(
            "SELECT path FROM frames WHERE video_id = ? ORDER BY timestamp_seconds LIMIT 3",
            (v["id"],),
        ).fetchall()

        tags = conn.execute(
            """
            SELECT t.name, t.category FROM tags t
            JOIN video_tags vt ON t.id = vt.tag_id
            WHERE vt.video_id = ?
        """,
            (v["id"],),
        ).fetchall()

        thumbs = ""
        for f in frames:
            thumbs += f'<img src="{f["path"]}" alt="">'
        if not frames:
            thumbs = ""

        tags_html = ""
        for t in tags:
            cat = t["category"] or "event"
            css_class = {
                "family": "tag-family",
                "travel": "tag-travel",
                "event": "tag-event",
                "novelty": "tag-novelty",
            }.get(cat, "tag-event")
            tags_html += f'<span class="tag {css_class}">{t["name"]}</span>'

        dur = format_duration(v["duration_seconds"])
        details = dur
        if v["face_count"]:
            details += f" &bull; {v['face_count']} face{'s' if v['face_count'] != 1 else ''}"

        video_cards += f"""
    <div class="video-card">
      <div class="thumbs">{thumbs}</div>
      <div class="meta">
        <div class="num"><a href="{v["filename"]}" class="video-link">#{v["number"]:03d}</a></div>
        <h4>{v["title"] or v["filename"]}</h4>
        <div class="details">{details}</div>
        {tags_html}
      </div>
    </div>"""

    # Build people cards
    people_cards = ""
    for p in people:
        face_crops = conn.execute(
            "SELECT path FROM faces WHERE person_id = ? LIMIT 4", (p["id"],)
        ).fetchall()

        face_thumbs = ""
        for fc in face_crops:
            face_thumbs += f'<img src="{fc["path"]}" alt="" style="width:50px;height:50px;object-fit:cover;border-radius:4px;border:1px solid var(--border);margin-right:4px;">'

        vids = conn.execute(
            """
            SELECT v.number, v.filename FROM videos v
            JOIN video_people vp ON v.id = vp.video_id
            WHERE vp.person_id = ?
            ORDER BY v.number
        """,
            (p["id"],),
        ).fetchall()
        vid_links = ", ".join(
            f'<a href="{v["filename"]}" class="video-link">{v["number"]:03d}</a>' for v in vids
        )

        people_cards += f"""
    <div class="person-card">
      <h4>{p["name"]}</h4>
      <div class="detail">{p["description"] or ""}</div>
      <div class="videos">Seen in: {vid_links if vid_links else "Not yet linked"}</div>
      <div style="margin-top:8px;">{face_thumbs}</div>
    </div>"""

    # Build places section by region
    regions = {}
    for pl in places:
        r = pl["region"] or "Other"
        if r not in regions:
            regions[r] = []
        regions[r].append(pl)

    places_html = ""
    for region, pls in regions.items():
        places_html += f'<h3>{region}</h3>\n<div class="places-grid">\n'
        for pl in pls:
            # Get a frame from one of the place's videos for the image
            place_vid = conn.execute(
                """
                SELECT f.path FROM frames f
                JOIN video_places vp ON f.video_id = vp.video_id
                WHERE vp.place_id = ?
                ORDER BY f.timestamp_seconds
                LIMIT 1
            """,
                (pl["id"],),
            ).fetchone()
            img = f'<img src="{place_vid["path"]}" alt="{pl["name"]}">' if place_vid else ""

            pl_vids = conn.execute(
                """
                SELECT v.number, v.filename FROM videos v
                JOIN video_places vpl ON v.id = vpl.video_id
                WHERE vpl.place_id = ?
                ORDER BY v.number
            """,
                (pl["id"],),
            ).fetchall()
            vid_links = ", ".join(
                f'<a href="{v["filename"]}" class="video-link">{v["number"]:03d}</a>'
                for v in pl_vids
            )

            places_html += f"""
    <div class="place-card">
      {img}
      <div class="info">
        <h4>{pl["name"]}</h4>
        <div class="loc-detail">{pl["description"] or ""}<br>Videos: {vid_links}</div>
      </div>
    </div>"""
        places_html += "</div>\n"

    # Build timeline
    years = conn.execute("""
        SELECT year, GROUP_CONCAT(number || '. ' || COALESCE(title, filename), '|') as vids,
               COUNT(*) as cnt
        FROM videos
        WHERE year IS NOT NULL
        GROUP BY year
        ORDER BY year
    """).fetchall()

    timeline_html = ""
    for y in years:
        items = y["vids"].split("|")
        items_html = ""
        for item in items:
            items_html += f"<li>{item}</li>\n"
        timeline_html += f"""
    <div class="timeline-item">
      <div class="year">{y["year"]}</div>
      <ul class="events">{items_html}</ul>
    </div>"""

    html = f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dad's Home Movies &mdash; 1940s&ndash;1978 Video Catalog</title>
<style>
  :root {{
    --bg: #1a1a2e;
    --card: #16213e;
    --accent: #e2b33e;
    --accent2: #c47a3a;
    --text: #eee;
    --muted: #8899aa;
    --border: #2a3a5e;
    --tag-family: #3a6b4f;
    --tag-travel: #4a5a8a;
    --tag-event: #7a4a5a;
    --tag-novelty: #5a5a3a;
  }}
  * {{ margin: 0; padding: 0; box-sizing: border-box; }}
  body {{ font-family: 'Georgia', 'Times New Roman', serif; background: var(--bg); color: var(--text); line-height: 1.6; }}
  a {{ color: var(--accent); text-decoration: none; }}
  a:hover {{ text-decoration: underline; }}
  .hero {{ text-align: center; padding: 60px 20px 40px; background: linear-gradient(180deg, #0f0f23 0%, var(--bg) 100%); border-bottom: 2px solid var(--accent); }}
  .hero h1 {{ font-size: 2.8em; color: var(--accent); font-weight: normal; letter-spacing: 2px; margin-bottom: 8px; }}
  .hero .subtitle {{ font-size: 1.2em; color: var(--muted); font-style: italic; }}
  .hero .stats {{ margin-top: 20px; display: flex; justify-content: center; gap: 40px; flex-wrap: wrap; }}
  .hero .stat {{ text-align: center; }}
  .hero .stat .num {{ font-size: 2em; color: var(--accent); display: block; }}
  .hero .stat .label {{ font-size: 0.85em; color: var(--muted); text-transform: uppercase; letter-spacing: 1px; }}
  nav {{ background: var(--card); border-bottom: 1px solid var(--border); padding: 12px 20px; position: sticky; top: 0; z-index: 100; text-align: center; }}
  nav a {{ color: var(--muted); margin: 0 15px; font-size: 0.9em; text-transform: uppercase; letter-spacing: 1px; }}
  nav a:hover {{ color: var(--accent); text-decoration: none; }}
  section {{ max-width: 1200px; margin: 0 auto; padding: 40px 20px; }}
  section h2 {{ font-size: 1.8em; color: var(--accent); border-bottom: 1px solid var(--border); padding-bottom: 10px; margin-bottom: 25px; font-weight: normal; }}
  section h3 {{ font-size: 1.3em; color: var(--accent2); margin: 25px 0 15px; font-weight: normal; }}
  .people-grid {{ display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px; }}
  .person-card {{ background: var(--card); border: 1px solid var(--border); border-radius: 8px; padding: 20px; }}
  .person-card h4 {{ color: var(--accent); font-size: 1.1em; margin-bottom: 6px; font-weight: normal; }}
  .person-card .detail {{ color: var(--muted); font-size: 0.9em; margin-bottom: 4px; }}
  .person-card .videos {{ font-size: 0.85em; color: var(--muted); margin-top: 8px; font-style: italic; }}
  .timeline {{ position: relative; padding-left: 40px; }}
  .timeline::before {{ content: ''; position: absolute; left: 15px; top: 0; bottom: 0; width: 2px; background: var(--border); }}
  .timeline-item {{ position: relative; margin-bottom: 30px; }}
  .timeline-item::before {{ content: ''; position: absolute; left: -30px; top: 6px; width: 12px; height: 12px; border-radius: 50%; background: var(--accent); border: 2px solid var(--bg); }}
  .timeline-item .year {{ font-size: 1.4em; color: var(--accent); }}
  .timeline-item .events {{ color: var(--text); font-size: 0.95em; margin-top: 4px; }}
  .timeline-item .events li {{ margin-bottom: 3px; list-style: none; }}
  .timeline-item .events li::before {{ content: '\\2014\\00a0'; color: var(--muted); }}
  .places-grid {{ display: grid; grid-template-columns: repeat(auto-fill, minmax(350px, 1fr)); gap: 20px; }}
  .place-card {{ background: var(--card); border: 1px solid var(--border); border-radius: 8px; overflow: hidden; }}
  .place-card img {{ width: 100%; height: 180px; object-fit: cover; display: block; }}
  .place-card .info {{ padding: 15px; }}
  .place-card .info h4 {{ color: var(--accent); font-weight: normal; font-size: 1.1em; margin-bottom: 4px; }}
  .place-card .info .loc-detail {{ color: var(--muted); font-size: 0.9em; }}
  .video-grid {{ display: grid; grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); gap: 20px; }}
  .video-card {{ background: var(--card); border: 1px solid var(--border); border-radius: 8px; overflow: hidden; }}
  .video-card:hover {{ border-color: var(--accent); }}
  .video-card .thumbs {{ display: flex; height: 120px; overflow: hidden; }}
  .video-card .thumbs img {{ flex: 1; object-fit: cover; min-width: 0; border-right: 1px solid var(--bg); }}
  .video-card .meta {{ padding: 12px 15px; }}
  .video-card .meta .num {{ color: var(--accent); font-size: 0.8em; letter-spacing: 1px; }}
  .video-card .meta h4 {{ color: var(--text); font-weight: normal; font-size: 1em; margin: 4px 0; }}
  .video-card .meta .details {{ color: var(--muted); font-size: 0.85em; }}
  .video-link {{ color: var(--accent); text-decoration: none; font-weight: bold; }}
  .video-link:hover {{ color: #fff; text-decoration: underline; }}
  .tag {{ display: inline-block; padding: 1px 8px; border-radius: 10px; font-size: 0.75em; margin-right: 4px; margin-top: 6px; }}
  .tag-family {{ background: var(--tag-family); }}
  .tag-travel {{ background: var(--tag-travel); }}
  .tag-event {{ background: var(--tag-event); }}
  .tag-novelty {{ background: var(--tag-novelty); }}
  .lightbox {{ display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.92); z-index: 1000; justify-content: center; align-items: center; cursor: pointer; }}
  .lightbox.active {{ display: flex; }}
  .lightbox img {{ max-width: 90vw; max-height: 90vh; border-radius: 4px; }}
  footer {{ text-align: center; padding: 30px; color: var(--muted); font-size: 0.85em; border-top: 1px solid var(--border); margin-top: 40px; }}
  @media (max-width: 600px) {{
    .hero h1 {{ font-size: 1.8em; }}
    .video-grid {{ grid-template-columns: 1fr; }}
    .places-grid {{ grid-template-columns: 1fr; }}
  }}
</style>
</head>
<body>

<div class="hero">
  <h1>Dad's Home Movies</h1>
  <div class="subtitle">A Family Film Archive &mdash; 1940s through 1978</div>
  <div class="stats">
    <div class="stat"><span class="num">{len(videos)}</span><span class="label">Videos</span></div>
    <div class="stat"><span class="num">{hours}+</span><span class="label">Hours</span></div>
    <div class="stat"><span class="num">{total_frames}</span><span class="label">Frames</span></div>
    <div class="stat"><span class="num">{total_faces}</span><span class="label">Faces Detected</span></div>
  </div>
</div>

<nav>
  <a href="#people">People</a>
  <a href="#timeline">Timeline</a>
  <a href="#places">Places</a>
  <a href="#videos">All Videos</a>
</nav>

<section id="people">
  <h2>People</h2>
  <div class="people-grid">{people_cards}</div>
</section>

<section id="timeline">
  <h2>Timeline</h2>
  <div class="timeline">{timeline_html}</div>
</section>

<section id="places">
  <h2>Places</h2>
  {places_html}
</section>

<section id="videos">
  <h2>All {len(videos)} Videos</h2>
  <div class="video-grid">{video_cards}</div>
</section>

<div class="lightbox" id="lightbox" onclick="this.classList.remove('active')">
  <img id="lightbox-img" src="" alt="">
</div>

<footer>
  <p>Catalog generated using Dad's Video Catalog (Python + OpenCV + SQLite)</p>
  <p>{total_frames} frames &bull; {total_faces} faces detected &bull; {len(people)} people identified</p>
</footer>

<script>
document.querySelectorAll('.video-card img, .place-card img').forEach(img => {{
  img.style.cursor = 'pointer';
  img.addEventListener('click', e => {{
    e.stopPropagation();
    document.getElementById('lightbox-img').src = img.src;
    document.getElementById('lightbox').classList.add('active');
  }});
}});
</script>
</body>
</html>"""

    output_path = PROJECT_ROOT / "catalog.html"
    output_path.write_text(html)
    print(
        f"Generated {output_path} ({len(videos)} videos, {total_frames} frames, {total_faces} faces)"
    )
    conn.close()


def generate_markdown():
    """Generate a Markdown catalog."""
    conn = get_db()

    videos = conn.execute("SELECT * FROM videos ORDER BY number").fetchall()
    people = conn.execute("""
        SELECT p.*, COUNT(DISTINCT vp.video_id) as video_count
        FROM people p
        LEFT JOIN video_people vp ON p.id = vp.person_id
        GROUP BY p.id
        ORDER BY p.name
    """).fetchall()

    places = conn.execute("""
        SELECT pl.*, COUNT(DISTINCT vpl.video_id) as video_count
        FROM places pl
        LEFT JOIN video_places vpl ON pl.id = vpl.place_id
        GROUP BY pl.id
        ORDER BY pl.region, pl.name
    """).fetchall()

    total_duration = sum(v["duration_seconds"] or 0 for v in videos)
    hours = int(total_duration // 3600)
    minutes = int((total_duration % 3600) // 60)

    frame_count = conn.execute("SELECT COUNT(*) FROM frames").fetchone()[0]
    face_count = conn.execute("SELECT COUNT(*) FROM faces").fetchone()[0]

    md = f"""# Dad's Home Movies - 1940s through 1978

A Family Film Archive | {len(videos)} Videos | {hours}h {minutes}m Total | {frame_count} Frames | {face_count} Faces Detected

---

## People

| Name | Description | Videos |
|------|-------------|--------|
"""
    for p in people:
        vids = conn.execute(
            """
            SELECT v.number FROM videos v
            JOIN video_people vp ON v.id = vp.video_id
            WHERE vp.person_id = ?
            ORDER BY v.number
        """,
            (p["id"],),
        ).fetchall()
        vid_nums = ", ".join(f"#{v['number']:03d}" for v in vids) if vids else "-"
        md += f"| **{p['name']}** | {p['description'] or ''} | {vid_nums} |\n"

    md += "\n---\n\n## Timeline\n\n"
    years = conn.execute("""
        SELECT year, GROUP_CONCAT(number || '. ' || COALESCE(title, filename), ', ') as vids,
               COUNT(*) as cnt
        FROM videos
        WHERE year IS NOT NULL
        GROUP BY year
        ORDER BY year
    """).fetchall()
    for y in years:
        md += f"### {y['year']}\n"
        for v in y["vids"].split(", "):
            md += f"- {v}\n"
        md += "\n"

    md += "---\n\n## Places\n\n"
    md += "| Place | Region | Description | Videos |\n"
    md += "|-------|--------|-------------|--------|\n"
    for pl in places:
        pl_vids = conn.execute(
            """
            SELECT v.number FROM videos v
            JOIN video_places vpl ON v.id = vpl.video_id
            WHERE vpl.place_id = ?
            ORDER BY v.number
        """,
            (pl["id"],),
        ).fetchall()
        vid_nums = ", ".join(f"#{v['number']:03d}" for v in pl_vids)
        md += f"| **{pl['name']}** | {pl['region'] or ''} | {pl['description'] or ''} | {vid_nums} |\n"

    md += "\n---\n\n## All Videos\n\n"
    md += "| # | Title | Duration | Year | Tags |\n"
    md += "|---|-------|----------|------|------|\n"
    for v in videos:
        tags = conn.execute(
            """
            SELECT t.name FROM tags t
            JOIN video_tags vt ON t.id = vt.tag_id
            WHERE vt.video_id = ?
        """,
            (v["id"],),
        ).fetchall()
        tag_str = ", ".join(t["name"] for t in tags)
        md += f"| {v['number']:03d} | {v['title'] or v['filename']} | {format_duration(v['duration_seconds'])} | {v['year'] or '-'} | {tag_str} |\n"

    md += "\n---\n\n*Generated by Dad's Video Catalog*\n"

    output_path = PROJECT_ROOT / "catalog.md"
    output_path.write_text(md)
    print(f"Generated {output_path}")
    conn.close()


def main():
    """Run report generation from the command line."""
    if len(sys.argv) < 2:
        print("Usage: python3 -m videocatalog.reports <command>")
        print("Commands: html, markdown (md), stats")
        sys.exit(1)

    cmd = sys.argv[1]
    if cmd == "html":
        generate_html()
    elif cmd in ("markdown", "md"):
        generate_markdown()
    elif cmd == "stats":
        print_stats()
    else:
        print(f"Unknown command: {cmd}")
        sys.exit(1)


if __name__ == "__main__":
    main()
