from __future__ import annotations

import datetime as dt
from pathlib import Path
from types import SimpleNamespace

from jinja2 import Environment, FileSystemLoader


def _ns(**kwargs):
    return SimpleNamespace(**kwargs)


def _build_data():
    overall = _ns(
        current=_ns(clicks=100, impressions=1000, ctr=0.1, position=5.0),
        pop_change=_ns(pct=_ns(clicks=5.0, impressions=-2.0, ctr=1.5, position=-3.0)),
        yoy_change=_ns(pct=_ns(clicks=10.0, impressions=4.0, ctr=-0.5, position=2.0)),
    )
    analytics_totals = _ns(
        ai=_ns(
            sessions=11,
            users=9,
            engaged_sessions=7,
            engagement_rate=0.64,
            avg_session_duration=8.2,
            views=21,
        ),
        direct=_ns(
            sessions=14,
            users=12,
            engaged_sessions=9,
            engagement_rate=0.5,
            avg_session_duration=6.0,
            views=30,
        ),
    )
    organic_totals = _ns(
        sessions=40,
        users=32,
        engaged_sessions=25,
        engagement_rate=0.62,
        avg_session_duration=9.8,
        views=90,
    )
    analytics_period = _ns(
        name="Last 7 days",
        totals=analytics_totals,
        direct_allocated=_ns(
            sessions=4,
            users=3,
            engaged_sessions=2,
            engagement_rate=0.5,
            avg_session_duration=6.0,
            views=9,
        ),
        organic_totals=organic_totals,
        trend=[_ns(date="2026-01-01", ai_sessions=5, organic_sessions=12)],
        ai_share=0.11,
        method="source_regex",
        direct_share=0.3,
        ai_breakdown={"chatgpt": _ns(sessions=6), "openai": _ns(sessions=5)},
        pop_totals=_ns(
            ai=_ns(
                sessions=10,
                users=8,
                engaged_sessions=6,
                engagement_rate=0.6,
                avg_session_duration=7.5,
                views=18,
            ),
        ),
        pop_organic_totals=_ns(
            sessions=35,
            users=30,
            engaged_sessions=22,
            engagement_rate=0.6,
            avg_session_duration=9.6,
            views=85,
        ),
        yoy_totals=_ns(
            ai=_ns(
                sessions=9,
                users=7,
                engaged_sessions=5,
                engagement_rate=0.55,
                avg_session_duration=7.0,
                views=16,
            ),
        ),
        yoy_organic_totals=_ns(
            sessions=38,
            users=31,
            engaged_sessions=24,
            engagement_rate=0.61,
            avg_session_duration=9.7,
            views=88,
        ),
    )
    period = _ns(
        name="Last 7 days",
        overall=overall,
        winning=[],
        losing=[],
        opportunities=[],
        daily_trend=[],
        analytics=analytics_period,
    )
    data = _ns(
        site_url="https://example.com",
        generated_at=dt.datetime(2026, 1, 1, 12, 0, 0),
        periods=[period],
        analytics=_ns(
            periods=[analytics_period],
            direct_share=0.3,
            source_regex="(chatgpt|openai)",
            channel_group_name="AI Channel Group",
            method="source_regex",
        ),
        indexing=_ns(valid=0, excluded=0, error=0, issues={}, sample_size=0),
        health=_ns(
            host_availability=100.0,
            avg_response_time=100.0,
            slow_pages=0,
            error_pages=0,
            total_checked=0,
            details=[],
        ),
    )
    return data


def test_executive_summary_includes_yoy_percentages():
    template_dir = Path(__file__).resolve().parents[1] / "worai" / "seoreport" / "templates"
    env = Environment(loader=FileSystemLoader(template_dir))
    template = env.get_template("report.html")

    rendered = template.render(data=_build_data())

    start = rendered.find("<h3>Executive Summary</h3>")
    end = rendered.find("<!-- Period Tabs -->")
    assert start != -1
    assert end != -1

    summary_section = rendered[start:end]
    assert summary_section.count("YoY") >= 4
    assert "CTR" in summary_section


def test_analytics_section_renders():
    template_dir = Path(__file__).resolve().parents[1] / "worai" / "seoreport" / "templates"
    env = Environment(loader=FileSystemLoader(template_dir))
    template = env.get_template("report.html")

    rendered = template.render(data=_build_data())

    assert "Organic" in rendered
