"""Fetch AI-related recommendations from ITU-T (free PDFs, no API).

ITU-T has no REST API. We use:
1. A curated catalog of known AI-related recommendations (Y-series, X-series)
2. The ITU handle system for metadata
3. Direct PDF downloads from itu.int
"""

from __future__ import annotations

import re
import time as time_mod

import httpx
from rich.console import Console

from ..config import Config
from .base import SourceDocument

console = Console()

# Known AI-relevant ITU-T Recommendations
# Source: ITU-T Study Groups 13 (Future Networks), 16 (Multimedia), 17 (Security), 20 (IoT)
# Format: (rec_id, title, series_topic)
ITU_AI_CATALOG = [
    # Y-series: Global information infrastructure, cloud computing, AI
    ("Y.3172", "Architectural framework for machine learning in future networks including IMT-2020",
     "AI/ML architecture"),
    ("Y.3173", "Framework for evaluating intelligence levels of future networks including IMT-2020",
     "AI/ML architecture"),
    ("Y.3174", "Framework for data handling to enable machine learning in future networks including IMT-2020",
     "AI/ML architecture"),
    ("Y.3176", "Machine learning marketplace integration in future networks including IMT-2020",
     "AI/ML architecture"),
    ("Y.3177", "Architectural framework of AI-as-a-Service to enable AI services in future networks",
     "AI/ML architecture"),
    ("Y.3178", "Requirements and framework of federated machine learning",
     "Federated learning"),
    ("Y.3179", "Architectural framework for AI-based network automation",
     "Network automation"),
    ("Y.3180", "Framework for multi-domain ML pipeline in future networks",
     "AI/ML architecture"),
    ("Y.3181", "Architectural framework for trustworthy networking based on machine learning technology",
     "Trustworthy AI"),
    ("Y.3530", "Cloud computing — Overview of machine learning in future networks",
     "Cloud AI"),
    ("Y.3531", "Cloud computing — Functional architecture for machine learning as a service",
     "Cloud AI"),
    ("Y.4464", "Framework for IoT-area network using autonomous agents",
     "IoT agents"),
    ("Y.4907", "Reference architecture for intelligent transportation systems communication network using AI",
     "AI transport"),
    # X-series: Security
    ("X.1381", "Framework for AI risk assessment in telecommunication networks",
     "AI security"),
    ("X.1382", "Security requirements for AI-based solutions in telecommunication networks",
     "AI security"),
    ("X.1383", "Assessment criteria for trustworthiness of AI-based telecommunication services",
     "Trustworthy AI"),
    ("X.1384", "Security threats and risk treatment measures for AI-based telecommunication systems",
     "AI security"),
    # Focus Group deliverables (FG-AI4H etc.)
    ("FG-AI4H DEL01", "AI for Health: Ethics and Governance",
     "AI health"),
    ("FG-AI4H DEL02", "AI for Health: Data handling",
     "AI health"),
    ("FG-AI4H DEL7.2", "AI for Health: Clinical evaluation of AI",
     "AI health"),
]

ITU_REC_BASE = "https://www.itu.int/rec/T-REC-"
ITU_HANDLE_BASE = "https://handle.itu.int/11.1002/1000"


def _rec_to_name(rec_id: str) -> str:
    """Convert ITU-T rec ID to slug. E.g. 'Y.3172' -> 'itu-t-y-3172'."""
    slug = rec_id.lower().replace(".", "-").replace(" ", "-").replace("/", "-")
    return f"itu-t-{slug}"


def _rec_to_url(rec_id: str) -> str:
    """Best-effort URL for an ITU-T recommendation."""
    if rec_id.startswith("FG-"):
        # Focus group deliverables have different URL patterns
        return f"https://www.itu.int/en/ITU-T/focusgroups/{rec_id.split()[0].lower()}/Pages/default.aspx"
    # Standard recommendations: T-REC-Y.3172
    return f"{ITU_REC_BASE}{rec_id.replace('.', '.')}"


class ITUFetcher:
    """Fetch AI-related specs from ITU-T.

    Uses a curated catalog since ITU-T has no search API.
    Can be extended by scraping ITU-T work programme pages.
    """

    def __init__(self, config: Config | None = None):
        self.config = config or Config.load()
        self.client = httpx.Client(timeout=30, follow_redirects=True)

    def search(
        self, keywords: list[str], since: str | None = None
    ) -> list[SourceDocument]:
        """Return AI-relevant ITU-T recommendations from curated catalog."""
        console.print("  Loading ITU-T AI recommendation catalog...")
        docs: list[SourceDocument] = []

        for rec_id, title, topic in ITU_AI_CATALOG:
            name = _rec_to_name(rec_id)
            url = _rec_to_url(rec_id)

            docs.append(SourceDocument(
                name=name,
                title=f"ITU-T {rec_id}: {title}",
                abstract=f"ITU-T Recommendation {rec_id} on {topic}: {title}",
                source="itu",
                source_id=rec_id,
                source_url=url,
                time="",
                doc_status="published",
                extra={"topic": topic},
            ))

        # Try to enrich with actual metadata from ITU website
        console.print(f"  Fetching metadata for {len(docs)} ITU-T recommendations...")
        enriched = 0
        for doc in docs:
            if self._enrich_metadata(doc):
                enriched += 1
            time_mod.sleep(0.3)

        console.print(f"  Found [bold green]{len(docs)}[/] ITU-T specs ({enriched} with metadata)")
        return docs

    def _enrich_metadata(self, doc: SourceDocument) -> bool:
        """Try to fetch real abstract/date from ITU website."""
        rec_id = doc.source_id
        if rec_id.startswith("FG-"):
            return False  # Focus groups have different structure

        try:
            # Try the recommendation page for scope/abstract
            url = f"https://www.itu.int/ITU-T/recommendations/rec.aspx?rec={rec_id}"
            resp = self.client.get(url)
            if resp.status_code == 200:
                html = resp.text
                # Extract summary/scope from page
                scope_match = re.search(
                    r'(?:Summary|Scope|Abstract)[:\s]*</[^>]+>\s*(.+?)(?:</|<br|<p)',
                    html, re.DOTALL | re.IGNORECASE,
                )
                if scope_match:
                    scope = re.sub(r'<[^>]+>', '', scope_match.group(1)).strip()
                    if len(scope) > 50:
                        doc.abstract = scope[:2000]

                # Extract date
                date_match = re.search(
                    r'(?:Approved|Published)[:\s]*(\d{4}-\d{2}-\d{2}|\d{4}-\d{2}|\d{4})',
                    html, re.IGNORECASE,
                )
                if date_match:
                    doc.time = date_match.group(1)
                return True
        except httpx.HTTPError:
            pass
        return False

    def download_text(self, doc: SourceDocument) -> str | None:
        """ITU-T recommendations are PDFs — download and extract if possible."""
        rec_id = doc.source_id
        if rec_id.startswith("FG-"):
            return None

        # Try to find the PDF download link
        try:
            # ITU recommendation pages have a download link
            url = f"https://www.itu.int/rec/dologin_pub.asp?lang=e&id=T-REC-{rec_id}&type=items"
            resp = self.client.get(url)
            if resp.status_code == 200 and "application/pdf" in resp.headers.get("content-type", ""):
                try:
                    from io import BytesIO
                    from pdfminer.high_level import extract_text
                    text = extract_text(BytesIO(resp.content))
                    return text[:100000] if text else None
                except ImportError:
                    return f"[PDF document: {doc.title}. Install pdfminer.six to extract text.]"
        except httpx.HTTPError as e:
            console.print(f"[dim]Could not download {doc.name}: {e}[/]")
        return None

    def close(self) -> None:
        self.client.close()
