"""
BIBIVIDI — CSRD Compliance Reporting (TODO-14)
Generates AI Scope 3 emissions reports for enterprise customers.

Exportable as CSV (machine-readable for filing tools) or HTML (human-readable
for ESG officers and auditors). No extra dependencies required.

Methodology
───────────
CO₂ conversion: tokens_saved × 0.003 gCO₂eq/token

This factor is derived from:
  - Patterson et al. (2022) "Carbon Footprint of Machine Learning" — NeurIPS
  - Green Software Foundation (2023) LLM inference energy benchmarks
  - IEA (2023) average world grid carbon intensity: 475 gCO₂/kWh

Disclaimer: This report uses an estimated conversion factor (0.003 gCO₂eq/token).
The actual factor varies by cloud provider, region, hardware, and model size.
Independent verification by a GHG auditor is recommended for formal CSRD
Scope 3 Category 11 (Use of Sold Products) filings.
"""
from __future__ import annotations

import calendar
import csv
import io
import logging
from dataclasses import dataclass
from datetime import UTC, datetime

import aiosqlite

from bvd.config import settings

logger = logging.getLogger(__name__)

# Grams of CO₂ equivalent avoided per token saved.
# Source: Green Software Foundation / Patterson et al. 2022 inference estimate.
CO2_FACTOR_G_PER_TOKEN: float = 0.003

METHODOLOGY_CITATION = (
    "CO₂ conversion factor: 0.003 gCO₂eq/token — derived from "
    "Patterson et al. (2022) 'Carbon Footprint of Machine Learning' (NeurIPS), "
    "Green Software Foundation (2023) LLM inference benchmarks, "
    "and IEA (2023) average world grid intensity (475 gCO₂/kWh)."
)

DISCLAIMER = (
    "DISCLAIMER: The CO₂ figures in this report are estimates based on a "
    "model-agnostic conversion factor. Actual emissions depend on cloud provider, "
    "data-centre region, hardware generation, and model architecture. "
    "This report is provided for informational purposes. Independent GHG auditor "
    "verification is recommended for formal CSRD Scope 3 filings."
)


@dataclass
class CsrdMonthlyReport:
    year: int
    month: int
    executions: int
    tokens_in: int          # total tokens processed before BIBIVIDI optimisation
    tokens_saved: int       # tokens NOT forwarded to the LLM (our reduction)
    saving_ratio: float     # tokens_saved / tokens_in (0–1)
    co2_factor_g_per_token: float
    co2_baseline_g: float   # tokens_in × factor (what the month would have emitted)
    co2_saved_g: float      # tokens_saved × factor (emissions avoided by BIBIVIDI)
    co2_net_g: float        # actual net AI inference emissions this month
    savings_eur: float      # gross EUR value of tokens saved (from billing calc)
    generated_at: str       # ISO-8601 timestamp
    methodology: str
    disclaimer: str

    @property
    def period_label(self) -> str:
        return f"{self.year}-{self.month:02d}"

    @property
    def co2_saved_kg(self) -> float:
        return self.co2_saved_g / 1000


async def build_csrd_report(year: int, month: int) -> CsrdMonthlyReport:
    """Query the executions table and build a CSRD report for the given month."""
    _, last_day = calendar.monthrange(year, month)
    start = datetime(year, month, 1, tzinfo=UTC).isoformat()
    end = datetime(year, month, last_day, 23, 59, 59, tzinfo=UTC).isoformat()

    async with aiosqlite.connect(settings.db_path) as db:  # type: ignore[arg-type]
        async with db.execute(
            """
            SELECT
                COUNT(*)                                              AS executions,
                COALESCE(SUM(tokens_before), 0)                      AS tokens_in,
                COALESCE(SUM(tokens_before - tokens_after), 0)       AS tokens_saved,
                COALESCE(SUM(
                    (tokens_before - tokens_after) *
                    COALESCE(model_price_per_token_eur, 0.000000092)
                ), 0)                                                AS savings_eur
            FROM executions
            WHERE executed_at >= ? AND executed_at <= ?
              AND tokens_before > tokens_after
            """,
            (start, end),
        ) as cur:
            row = await cur.fetchone()

    executions = int(row[0]) if row else 0
    tokens_in = int(row[1]) if row else 0
    tokens_saved = int(row[2]) if row else 0
    savings_eur = float(row[3]) if row else 0.0
    saving_ratio = (tokens_saved / tokens_in) if tokens_in else 0.0

    co2_baseline_g = tokens_in * CO2_FACTOR_G_PER_TOKEN
    co2_saved_g = tokens_saved * CO2_FACTOR_G_PER_TOKEN
    co2_net_g = co2_baseline_g - co2_saved_g

    return CsrdMonthlyReport(
        year=year,
        month=month,
        executions=executions,
        tokens_in=tokens_in,
        tokens_saved=tokens_saved,
        saving_ratio=round(saving_ratio, 4),
        co2_factor_g_per_token=CO2_FACTOR_G_PER_TOKEN,
        co2_baseline_g=round(co2_baseline_g, 3),
        co2_saved_g=round(co2_saved_g, 3),
        co2_net_g=round(co2_net_g, 3),
        savings_eur=round(savings_eur, 4),
        generated_at=datetime.now(UTC).isoformat(),
        methodology=METHODOLOGY_CITATION,
        disclaimer=DISCLAIMER,
    )


def to_csv(report: CsrdMonthlyReport) -> str:
    """Export the report as CSRD-compatible CSV (UTF-8, semicolon-delimited)."""
    buf = io.StringIO()
    w = csv.writer(buf, delimiter=";")

    # Header block
    w.writerow(["BIBIVIDI CSRD AI Scope 3 Emissions Report"])
    w.writerow(["Report period", report.period_label])
    w.writerow(["Generated at", report.generated_at])
    w.writerow([])

    # Data
    w.writerow(["Metric", "Value", "Unit"])
    w.writerow(["Requests processed", report.executions, "count"])
    w.writerow(["Total tokens processed (before BIBIVIDI)", report.tokens_in, "tokens"])
    w.writerow(["Tokens saved (not forwarded to LLM)", report.tokens_saved, "tokens"])
    w.writerow(["Token reduction ratio", f"{report.saving_ratio * 100:.2f}", "%"])
    w.writerow(["CO₂eq baseline (without BIBIVIDI)", f"{report.co2_baseline_g:.3f}", "gCO₂eq"])
    w.writerow(["CO₂eq avoided by BIBIVIDI", f"{report.co2_saved_g:.3f}", "gCO₂eq"])
    w.writerow(["CO₂eq avoided by BIBIVIDI", f"{report.co2_saved_kg:.6f}", "kgCO₂eq"])
    w.writerow(["Net AI inference CO₂eq this period", f"{report.co2_net_g:.3f}", "gCO₂eq"])
    w.writerow(["Gross cost savings", f"{report.savings_eur:.4f}", "EUR"])
    w.writerow([])

    # Methodology + disclaimer
    w.writerow(["Methodology"])
    w.writerow([report.methodology])
    w.writerow([])
    w.writerow(["Disclaimer"])
    w.writerow([report.disclaimer])

    return buf.getvalue()


def to_html(report: CsrdMonthlyReport) -> str:
    """Export the report as a standalone HTML document suitable for ESG filing."""
    def _fmt_g(g: float) -> str:
        if g >= 1_000_000:
            return f"{g / 1_000_000:.3f} tCO₂eq"
        if g >= 1000:
            return f"{g / 1000:.3f} kgCO₂eq"
        return f"{g:.3f} gCO₂eq"

    def _fmt_tokens(n: int) -> str:
        if n >= 1_000_000_000:
            return f"{n / 1_000_000_000:.3f}B"
        if n >= 1_000_000:
            return f"{n / 1_000_000:.3f}M"
        if n >= 1000:
            return f"{n / 1000:.1f}K"
        return str(n)

    reduction_pct = f"{report.saving_ratio * 100:.1f}"
    co2_saved_fmt = _fmt_g(report.co2_saved_g)
    co2_baseline_fmt = _fmt_g(report.co2_baseline_g)
    co2_net_fmt = _fmt_g(report.co2_net_g)

    return f"""<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>BIBIVIDI CSRD Report — {report.period_label}</title>
  <style>
    body {{ font-family: system-ui, -apple-system, sans-serif; margin: 0; padding: 0;
           background: #f8f9fa; color: #212529; }}
    .header {{ background: #1a1a2e; color: white; padding: 2rem 3rem; }}
    .header h1 {{ margin: 0; font-size: 1.5rem; }}
    .header .subtitle {{ color: #adb5bd; margin: 0.25rem 0 0; }}
    .container {{ max-width: 900px; margin: 2rem auto; padding: 0 2rem; }}
    .card {{ background: white; border-radius: 8px; padding: 1.5rem; margin-bottom: 1.5rem;
             box-shadow: 0 1px 3px rgba(0,0,0,0.1); }}
    .card h2 {{ margin-top: 0; font-size: 1rem; text-transform: uppercase;
                letter-spacing: 0.05em; color: #6c757d; }}
    .metrics-grid {{ display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem; }}
    .metric {{ text-align: center; padding: 1rem; background: #f8f9fa; border-radius: 6px; }}
    .metric .value {{ font-size: 1.75rem; font-weight: 700; color: #1a1a2e; }}
    .metric .label {{ font-size: 0.8rem; color: #6c757d; margin-top: 0.25rem; }}
    .metric.highlight .value {{ color: #2d6a4f; }}
    table {{ width: 100%; border-collapse: collapse; }}
    th, td {{ padding: 0.6rem 0.75rem; text-align: left; border-bottom: 1px solid #dee2e6; }}
    th {{ background: #f8f9fa; font-weight: 600; font-size: 0.875rem; color: #495057; }}
    .disclaimer {{ font-size: 0.8rem; color: #6c757d; line-height: 1.5; }}
    .badge {{ display: inline-block; padding: 0.2em 0.6em; border-radius: 4px;
              font-size: 0.75rem; font-weight: 600; }}
    .badge-green {{ background: #d1e7dd; color: #0f5132; }}
    .footer {{ text-align: center; color: #adb5bd; font-size: 0.8rem; margin: 2rem 0; }}
  </style>
</head>
<body>
  <div class="header">
    <h1>BIBIVIDI — AI Scope 3 Emissions Report</h1>
    <p class="subtitle">
      Period: {report.period_label} &nbsp;·&nbsp;
      Generated: {report.generated_at[:19].replace("T", " ")} UTC &nbsp;·&nbsp;
      CSRD Scope 3 Category 11 (Use of Sold Products)
    </p>
  </div>

  <div class="container">

    <!-- KPI summary -->
    <div class="card">
      <h2>Monthly Summary</h2>
      <div class="metrics-grid">
        <div class="metric highlight">
          <div class="value">{co2_saved_fmt}</div>
          <div class="label">CO₂eq Avoided by BIBIVIDI</div>
        </div>
        <div class="metric">
          <div class="value">{_fmt_tokens(report.tokens_saved)}</div>
          <div class="label">Tokens Saved</div>
        </div>
        <div class="metric">
          <div class="value">{reduction_pct}%</div>
          <div class="label">Token Reduction</div>
        </div>
      </div>
    </div>

    <!-- Detailed breakdown -->
    <div class="card">
      <h2>AI Inference Emissions Breakdown</h2>
      <table>
        <thead>
          <tr><th>Metric</th><th>Value</th><th>Unit</th></tr>
        </thead>
        <tbody>
          <tr>
            <td>API requests intercepted</td>
            <td><strong>{report.executions:,}</strong></td>
            <td>requests</td>
          </tr>
          <tr>
            <td>Tokens processed (before BIBIVIDI)</td>
            <td>{report.tokens_in:,}</td>
            <td>tokens</td>
          </tr>
          <tr>
            <td>Tokens NOT forwarded to LLM</td>
            <td>{report.tokens_saved:,}</td>
            <td>tokens</td>
          </tr>
          <tr>
            <td>Token reduction ratio</td>
            <td><strong>{reduction_pct}%</strong></td>
            <td></td>
          </tr>
          <tr>
            <td>CO₂eq baseline (without BIBIVIDI)</td>
            <td>{co2_baseline_fmt}</td>
            <td>estimated</td>
          </tr>
          <tr>
            <td>CO₂eq avoided <span class="badge badge-green">Scope 3 reduction</span></td>
            <td><strong>{co2_saved_fmt}</strong></td>
            <td>estimated</td>
          </tr>
          <tr>
            <td>Net AI inference CO₂eq this period</td>
            <td>{co2_net_fmt}</td>
            <td>estimated</td>
          </tr>
          <tr>
            <td>Gross cost savings</td>
            <td>€{report.savings_eur:.4f}</td>
            <td>EUR</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- Methodology -->
    <div class="card">
      <h2>Methodology</h2>
      <p style="font-size:0.9rem; line-height:1.6;">{report.methodology}</p>
      <p style="font-size:0.9rem;">
        CO₂ conversion factor: <strong>{report.co2_factor_g_per_token} gCO₂eq / token</strong>
      </p>
    </div>

    <!-- Disclaimer -->
    <div class="card">
      <h2>Disclaimer</h2>
      <p class="disclaimer">{report.disclaimer}</p>
    </div>

  </div>
  <div class="footer">
    Generated by BIBIVIDI &nbsp;·&nbsp; bibividi.ai &nbsp;·&nbsp;
    AI token optimization &amp; Scope 3 emissions tracking
  </div>
</body>
</html>"""
