#!python
from __future__ import annotations

import argparse
import json
import os
import re
import sqlite3
import sys
from dataclasses import dataclass, replace
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterable, Iterator


SCHEMA_VERSION = "kuzystats.v1"
UUID_RE = re.compile(
    r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-"
    r"[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
)
CLAUDE_METADATA_TAIL_BYTES = 2 * 1024 * 1024
READ_CHUNK_BYTES = 256 * 1024


@dataclass(frozen=True)
class SessionRecord:
    backend: str
    session_id: str
    session_name: str | None
    aliases: tuple[str, ...]
    title: str | None
    workdir: str | None
    state: str | None
    transcript_path: Path | None
    index_path: Path | None
    name_index_path: Path | None
    indexed_model: str | None = None
    indexed_effort: str | None = None
    indexed_at: str | None = None


@dataclass(frozen=True)
class ModelObservation:
    model: str
    effort: str | None
    observed_at: str | None
    metadata_type: str
    source_path: Path
    usage: dict[str, Any] | None = None
    rate_limits: dict[str, Any] | None = None
    last_error: dict[str, Any] | None = None


@dataclass(frozen=True)
class ClaudeMetadata:
    custom_title: str | None
    slug: str | None
    workdir: str | None


def codex_home() -> Path:
    configured = (
        os.environ.get("KUZYSTATS_CODEX_HOME")
        or os.environ.get("SESSION_MODEL_CODEX_HOME")
        or os.environ.get("CODEX_HOME")
    )
    return Path(configured) if configured else Path.home() / ".codex"


def claude_home() -> Path:
    configured = (
        os.environ.get("KUZYSTATS_CLAUDE_HOME")
        or os.environ.get("SESSION_MODEL_CLAUDE_HOME")
        or os.environ.get("CLAUDE_CONFIG_DIR")
    )
    return Path(configured) if configured else Path.home() / ".claude"


def json_object(raw: bytes) -> dict[str, Any] | None:
    try:
        value = json.loads(raw)
    except (UnicodeDecodeError, json.JSONDecodeError):
        return None
    return value if isinstance(value, dict) else None


def iter_json_lines(path: Path) -> Iterator[dict[str, Any]]:
    try:
        with path.open("rb") as handle:
            for line in handle:
                value = json_object(line)
                if value is not None:
                    yield value
    except OSError:
        return


def iter_json_lines_reverse(
    path: Path,
    *,
    byte_limit: int | None = None,
) -> Iterator[dict[str, Any]]:
    try:
        size = path.stat().st_size
        lower_bound = max(0, size - byte_limit) if byte_limit is not None else 0
        with path.open("rb") as handle:
            position = size
            remainder = b""
            while position > lower_bound:
                read_start = max(lower_bound, position - READ_CHUNK_BYTES)
                handle.seek(read_start)
                chunk = handle.read(position - read_start)
                position = read_start
                pieces = (chunk + remainder).split(b"\n")
                remainder = pieces[0]
                for line in reversed(pieces[1:]):
                    value = json_object(line)
                    if value is not None:
                        yield value
            if lower_bound == 0 and remainder:
                value = json_object(remainder)
                if value is not None:
                    yield value
    except OSError:
        return


def safe_glob(root: Path, pattern: str) -> list[Path]:
    try:
        return [path for path in root.glob(pattern) if path.is_file()]
    except OSError:
        return []


def normalized_string(value: Any) -> str | None:
    if not isinstance(value, str):
        return None
    normalized = value.strip()
    return normalized or None


def iso_from_epoch_ms(value: Any) -> str | None:
    if not isinstance(value, int) or value <= 0:
        return None
    return datetime.fromtimestamp(value / 1000, tz=timezone.utc).isoformat().replace(
        "+00:00", "Z"
    )


def codex_session_names(root: Path) -> tuple[dict[str, str], Path | None]:
    index_path = root / "session_index.jsonl"
    names: dict[str, str] = {}
    for record in iter_json_lines(index_path):
        session_id = normalized_string(record.get("id"))
        thread_name = normalized_string(record.get("thread_name"))
        if (
            session_id is not None
            and UUID_RE.fullmatch(session_id)
            and thread_name is not None
        ):
            names[session_id.lower()] = thread_name
    return names, index_path if index_path.is_file() else None


def sqlite_expression(columns: set[str], name: str, fallback: str = "NULL") -> str:
    return name if name in columns else f"{fallback} AS {name}"


def codex_database_records(path: Path) -> list[dict[str, Any]]:
    try:
        connection = sqlite3.connect(f"file:{path}?mode=ro", uri=True, timeout=0.2)
    except sqlite3.Error:
        return []
    try:
        columns = {
            str(row[1])
            for row in connection.execute("PRAGMA table_info(threads)")
            if len(row) > 1
        }
        if "id" not in columns:
            return []
        requested = [
            sqlite_expression(columns, "id"),
            sqlite_expression(columns, "name"),
            sqlite_expression(columns, "title"),
            sqlite_expression(columns, "model"),
            sqlite_expression(columns, "reasoning_effort"),
            sqlite_expression(columns, "cwd"),
            sqlite_expression(columns, "rollout_path"),
            sqlite_expression(columns, "archived", "0"),
            sqlite_expression(columns, "updated_at_ms", "0"),
        ]
        cursor = connection.execute(f"SELECT {', '.join(requested)} FROM threads")
        keys = (
            "id",
            "name",
            "title",
            "model",
            "reasoning_effort",
            "cwd",
            "rollout_path",
            "archived",
            "updated_at_ms",
        )
        return [dict(zip(keys, row, strict=True)) for row in cursor]
    except sqlite3.Error:
        return []
    finally:
        connection.close()


def codex_state_databases(root: Path) -> list[Path]:
    paths = safe_glob(root, "state_*.sqlite")
    return sorted(paths, key=lambda path: path.stat().st_mtime, reverse=True)


def codex_records() -> list[SessionRecord]:
    root = codex_home()
    names, name_index_path = codex_session_names(root)
    by_id: dict[str, tuple[int, SessionRecord]] = {}
    for database_path in codex_state_databases(root):
        for row in codex_database_records(database_path):
            session_id = normalized_string(row.get("id"))
            if session_id is None or not UUID_RE.fullmatch(session_id):
                continue
            session_id = session_id.lower()
            updated_at_ms = row.get("updated_at_ms")
            rank = updated_at_ms if isinstance(updated_at_ms, int) else 0
            native_name = names.get(session_id) or normalized_string(row.get("name"))
            transcript = normalized_string(row.get("rollout_path"))
            archived = bool(row.get("archived"))
            record = SessionRecord(
                backend="codex",
                session_id=session_id,
                session_name=native_name,
                aliases=(native_name,) if native_name else (),
                title=normalized_string(row.get("title")),
                workdir=normalized_string(row.get("cwd")),
                state="archived" if archived else "recorded",
                transcript_path=Path(transcript) if transcript else None,
                index_path=database_path,
                name_index_path=name_index_path,
                indexed_model=normalized_string(row.get("model")),
                indexed_effort=normalized_string(row.get("reasoning_effort")),
                indexed_at=iso_from_epoch_ms(updated_at_ms),
            )
            current = by_id.get(session_id)
            if current is None or rank > current[0]:
                by_id[session_id] = (rank, record)

    for session_id, native_name in names.items():
        if session_id in by_id:
            continue
        paths = safe_glob(root / "sessions", f"**/rollout-*{session_id}.jsonl")
        transcript = max(paths, key=lambda path: path.stat().st_mtime) if paths else None
        by_id[session_id] = (
            0,
            SessionRecord(
                backend="codex",
                session_id=session_id,
                session_name=native_name,
                aliases=(native_name,),
                title=None,
                workdir=None,
                state="recorded",
                transcript_path=transcript,
                index_path=None,
                name_index_path=name_index_path,
            ),
        )
    return [item[1] for item in by_id.values()]


def codex_transcript_for_uuid(session_id: str) -> Path | None:
    paths = safe_glob(codex_home() / "sessions", f"**/rollout-*{session_id}.jsonl")
    return max(paths, key=lambda path: path.stat().st_mtime) if paths else None


def codex_unindexed_record(session_id: str) -> SessionRecord | None:
    transcript = codex_transcript_for_uuid(session_id)
    if transcript is None:
        return None
    workdir = None
    title = None
    for record in iter_json_lines(transcript):
        if record.get("type") != "session_meta":
            continue
        payload = record.get("payload")
        if not isinstance(payload, dict):
            continue
        workdir = normalized_string(payload.get("cwd"))
        title = normalized_string(payload.get("title"))
        break
    return SessionRecord(
        backend="codex",
        session_id=session_id,
        session_name=None,
        aliases=(),
        title=title,
        workdir=workdir,
        state="recorded",
        transcript_path=transcript,
        index_path=None,
        name_index_path=None,
    )


def claude_transcript_paths() -> list[Path]:
    root = claude_home() / "projects"
    return sorted(
        (
            path
            for path in safe_glob(root, "*/*.jsonl")
            if UUID_RE.fullmatch(path.stem)
        ),
        key=lambda path: path.stat().st_mtime,
        reverse=True,
    )


def claude_metadata(path: Path, *, full_title_scan: bool = False) -> ClaudeMetadata:
    custom_title = None
    slug = None
    workdir = None
    byte_limit = None if full_title_scan else CLAUDE_METADATA_TAIL_BYTES
    for record in iter_json_lines_reverse(path, byte_limit=byte_limit):
        if custom_title is None and record.get("type") == "custom-title":
            custom_title = normalized_string(record.get("customTitle"))
        if slug is None:
            slug = normalized_string(record.get("slug"))
        if workdir is None:
            workdir = normalized_string(record.get("cwd"))
        if custom_title is not None and slug is not None and workdir is not None:
            break
    return ClaudeMetadata(
        custom_title=custom_title,
        slug=slug,
        workdir=workdir,
    )


def file_contains_claude_title(path: Path, query: str) -> bool:
    encoded = json.dumps(query, ensure_ascii=False, separators=(",", ":")).encode()
    needle = b'"customTitle":' + encoded
    overlap = b""
    try:
        with path.open("rb") as handle:
            while chunk := handle.read(READ_CHUNK_BYTES):
                data = overlap + chunk
                if needle in data:
                    return True
                overlap = data[-max(0, len(needle) - 1) :]
    except OSError:
        return False
    return False


def claude_record(path: Path, *, name_query: str | None = None) -> SessionRecord:
    metadata = claude_metadata(path)
    aliases = {value for value in (metadata.custom_title, metadata.slug) if value}
    if (
        name_query is not None
        and not any(alias.casefold() == name_query.casefold() for alias in aliases)
        and file_contains_claude_title(path, name_query)
    ):
        metadata = claude_metadata(path, full_title_scan=True)
        aliases = {value for value in (metadata.custom_title, metadata.slug) if value}
    session_name = metadata.custom_title or metadata.slug
    return SessionRecord(
        backend="claude",
        session_id=path.stem.lower(),
        session_name=session_name,
        aliases=tuple(sorted(aliases)),
        title=metadata.custom_title,
        workdir=metadata.workdir,
        state="recorded",
        transcript_path=path,
        index_path=None,
        name_index_path=None,
    )


def claude_records(name_query: str | None = None) -> list[SessionRecord]:
    return [
        claude_record(path, name_query=name_query) for path in claude_transcript_paths()
    ]


def codex_observation(record: SessionRecord) -> ModelObservation | None:
    path = record.transcript_path
    if path is not None:
        model = None
        effort = None
        observed_at = None
        usage = None
        rate_limits = None
        for item in iter_json_lines_reverse(path):
            payload = item.get("payload")
            if item.get("type") == "event_msg" and isinstance(payload, dict):
                if usage is None and payload.get("type") == "token_count":
                    info = payload.get("info")
                    if isinstance(info, dict):
                        totals = info.get("total_token_usage")
                        last_turn = info.get("last_token_usage")
                        usage = {
                            "scope": "session_total",
                            **(totals if isinstance(totals, dict) else {}),
                            "last_turn": last_turn if isinstance(last_turn, dict) else None,
                            "model_context_window": info.get("model_context_window"),
                        }
                    limits = payload.get("rate_limits")
                    rate_limits = limits if isinstance(limits, dict) else None
            if (
                model is None
                and item.get("type") == "turn_context"
                and isinstance(payload, dict)
            ):
                model = normalized_string(payload.get("model"))
                if model is not None:
                    effort = normalized_string(payload.get("effort"))
                    observed_at = normalized_string(item.get("timestamp"))
            if model is not None and usage is not None:
                break
        if model is not None:
            return ModelObservation(
                model=model,
                effort=effort,
                observed_at=observed_at,
                metadata_type="turn_context",
                source_path=path,
                usage=usage,
                rate_limits=rate_limits,
            )
    if record.indexed_model is None or record.index_path is None:
        return None
    return ModelObservation(
        model=record.indexed_model,
        effort=record.indexed_effort,
        observed_at=record.indexed_at,
        metadata_type="thread_index",
        source_path=record.index_path,
    )


def token_value(value: Any) -> int:
    return value if isinstance(value, int) and not isinstance(value, bool) else 0


def add_claude_usage(
    totals: dict[str, int],
    usage: dict[str, Any],
) -> None:
    for key in (
        "input_tokens",
        "cache_creation_input_tokens",
        "cache_read_input_tokens",
        "output_tokens",
    ):
        totals[key] += token_value(usage.get(key))
    server_tools = usage.get("server_tool_use")
    if isinstance(server_tools, dict):
        totals["web_search_requests"] += token_value(
            server_tools.get("web_search_requests")
        )
        totals["web_fetch_requests"] += token_value(
            server_tools.get("web_fetch_requests")
        )


def claude_usage_payload(
    totals: dict[str, int],
    *,
    message_count: int,
    last_turn: dict[str, Any] | None,
    by_model: dict[str, dict[str, int]],
) -> dict[str, Any]:
    total_input = (
        totals["input_tokens"]
        + totals["cache_creation_input_tokens"]
        + totals["cache_read_input_tokens"]
    )
    return {
        "scope": "session_aggregate",
        "message_count": message_count,
        **totals,
        "total_input_tokens": total_input,
        "total_tokens": total_input + totals["output_tokens"],
        "last_turn": last_turn,
        "by_model": {
            model: claude_usage_payload(
                values,
                message_count=values["message_count"],
                last_turn=None,
                by_model={},
            )
            for model, values in sorted(by_model.items())
        },
    }


def claude_observation(record: SessionRecord) -> ModelObservation | None:
    path = record.transcript_path
    if path is None:
        return None
    model = None
    effort = None
    observed_at = None
    last_turn = None
    last_error = None
    message_count = 0
    seen_message_ids: set[str] = set()
    totals = {
        "input_tokens": 0,
        "cache_creation_input_tokens": 0,
        "cache_read_input_tokens": 0,
        "output_tokens": 0,
        "web_search_requests": 0,
        "web_fetch_requests": 0,
    }
    by_model: dict[str, dict[str, int]] = {}
    for item in iter_json_lines_reverse(path):
        if item.get("type") != "assistant":
            continue
        message = item.get("message")
        if not isinstance(message, dict):
            continue
        item_model = normalized_string(message.get("model"))
        if item_model is None:
            continue
        if item_model.startswith("<"):
            if last_error is None and item.get("error"):
                content = message.get("content")
                text = None
                if isinstance(content, list):
                    for block in content:
                        if isinstance(block, dict) and block.get("type") == "text":
                            text = normalized_string(block.get("text"))
                            if text is not None:
                                break
                last_error = {
                    "status": item.get("apiErrorStatus"),
                    "code": item.get("error"),
                    "message": text,
                    "observed_at": normalized_string(item.get("timestamp")),
                }
            continue
        if model is None:
            model = item_model
            effort = normalized_string(message.get("effort")) or normalized_string(
                item.get("effort")
            )
            observed_at = normalized_string(item.get("timestamp"))
        message_id = normalized_string(message.get("id"))
        if message_id is not None and message_id in seen_message_ids:
            continue
        if message_id is not None:
            seen_message_ids.add(message_id)
        usage = message.get("usage")
        if not isinstance(usage, dict):
            continue
        if last_turn is None:
            last_turn = {
                key: usage.get(key)
                for key in (
                    "input_tokens",
                    "cache_creation_input_tokens",
                    "cache_read_input_tokens",
                    "output_tokens",
                    "service_tier",
                    "speed",
                    "inference_geo",
                )
                if key in usage
            }
        message_count += 1
        add_claude_usage(totals, usage)
        model_totals = by_model.setdefault(
            item_model,
            {
                "message_count": 0,
                "input_tokens": 0,
                "cache_creation_input_tokens": 0,
                "cache_read_input_tokens": 0,
                "output_tokens": 0,
                "web_search_requests": 0,
                "web_fetch_requests": 0,
            },
        )
        model_totals["message_count"] += 1
        add_claude_usage(model_totals, usage)
    if model is None:
        return None
    return ModelObservation(
        model=model,
        effort=effort,
        observed_at=observed_at,
        metadata_type="assistant_message",
        source_path=path,
        usage=claude_usage_payload(
            totals,
            message_count=message_count,
            last_turn=last_turn,
            by_model=by_model,
        ),
        last_error=last_error,
    )


def name_matches(record: SessionRecord, query: str) -> bool:
    folded = query.casefold()
    return any(alias.casefold() == folded for alias in record.aliases)


def deduplicate(records: Iterable[SessionRecord]) -> list[SessionRecord]:
    by_identity: dict[tuple[str, str], SessionRecord] = {}
    for record in records:
        key = (record.backend, record.session_id)
        current = by_identity.get(key)
        if current is None:
            by_identity[key] = record
            continue
        aliases = tuple(sorted(set(current.aliases) | set(record.aliases)))
        preferred = current
        if record.transcript_path is not None and (
            current.transcript_path is None
            or record.transcript_path.stat().st_mtime
            > current.transcript_path.stat().st_mtime
        ):
            preferred = record
        by_identity[key] = replace(preferred, aliases=aliases)
    return list(by_identity.values())


def resolve(query: str, backend: str) -> list[SessionRecord]:
    is_uuid = bool(UUID_RE.fullmatch(query))
    normalized_query = query.lower() if is_uuid else query
    matches: list[SessionRecord] = []

    if backend in {"auto", "codex"}:
        records = codex_records()
        if is_uuid:
            codex_matches = [
                record for record in records if record.session_id == normalized_query
            ]
            if not codex_matches:
                unindexed = codex_unindexed_record(normalized_query)
                if unindexed is not None:
                    codex_matches = [unindexed]
            matches.extend(codex_matches)
        else:
            matches.extend(record for record in records if name_matches(record, query))

    if backend in {"auto", "claude"}:
        records = claude_records(name_query=None if is_uuid else query)
        if is_uuid:
            matches.extend(
                record for record in records if record.session_id == normalized_query
            )
        else:
            matches.extend(record for record in records if name_matches(record, query))

    return deduplicate(matches)


def error_payload(query: str, code: str, message: str, **extra: Any) -> dict[str, Any]:
    return {
        "schema_version": SCHEMA_VERSION,
        "ok": False,
        "query": query,
        "error": {
            "code": code,
            "message": message,
            **extra,
        },
    }


def inspect_session(query: str, backend: str) -> tuple[dict[str, Any], int]:
    query = query.strip()
    if not query or "\x00" in query:
        return error_payload(
            query,
            "invalid_query",
            "Query must be a canonical UUID or a non-empty native session name.",
        ), 2

    matches = resolve(query, backend)
    if not matches:
        return error_payload(
            query,
            "session_not_found",
            "No native Codex or Claude session matched the UUID or session name.",
            backend=backend,
        ), 1
    if len(matches) > 1:
        return error_payload(
            query,
            "ambiguous_session",
            "The query matches more than one native session. Pass --backend or use the UUID.",
            matches=[
                {
                    "backend": match.backend,
                    "session_id": match.session_id,
                    "session_name": match.session_name,
                }
                for match in matches
            ],
        ), 2

    record = matches[0]
    observation = (
        codex_observation(record)
        if record.backend == "codex"
        else claude_observation(record)
    )
    if observation is None:
        return error_payload(
            query,
            "model_metadata_not_found",
            "The session exists, but its native metadata contains no model observation.",
            backend=record.backend,
            session_id=record.session_id,
            session_name=record.session_name,
        ), 1

    return {
        "schema_version": SCHEMA_VERSION,
        "ok": True,
        "query": query,
        "backend": record.backend,
        "session_id": record.session_id,
        "session_name": record.session_name,
        "aliases": list(record.aliases),
        "title": record.title,
        "model": observation.model,
        "effort": observation.effort,
        "model_observed_at": observation.observed_at,
        "metadata_type": observation.metadata_type,
        "usage": observation.usage,
        "rate_limits": observation.rate_limits,
        "last_error": observation.last_error,
        "session_state": record.state,
        "workdir": record.workdir,
        "source_path": str(observation.source_path),
        "transcript_path": (
            str(record.transcript_path) if record.transcript_path is not None else None
        ),
        "index_path": str(record.index_path) if record.index_path is not None else None,
        "name_index_path": (
            str(record.name_index_path)
            if record.name_index_path is not None
            else None
        ),
    }, 0


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description="Report native Codex or Claude session statistics as JSON."
    )
    parser.add_argument("session", help="Canonical UUID or native runtime session name.")
    parser.add_argument(
        "--backend",
        choices=("auto", "codex", "claude"),
        default="auto",
        help="Limit lookup to one runtime backend. Default: auto.",
    )
    parser.add_argument("--pretty", action="store_true", help="Pretty-print JSON output.")
    return parser


def main(argv: list[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    payload, returncode = inspect_session(args.session, args.backend)
    print(
        json.dumps(
            payload,
            indent=2 if args.pretty else None,
            sort_keys=True,
            separators=None if args.pretty else (",", ":"),
        )
    )
    return returncode


if __name__ == "__main__":
    sys.exit(main())
