"""
Symbol Sense Plugin for EZ-Input

Stores symbol-sensing sessions (3 numbers + Soul Palace + name/location hash)
and exposes endpoints for retrieval and verification.
"""

import hashlib
import json
import time
from datetime import datetime
from pathlib import Path
from typing import Any

from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel, Field

from ..plugin import Plugin

router = APIRouter(prefix="/symbol-sense", tags=["symbol-sense"])

DATA_DIR = Path(__file__).resolve().parent.parent / "data"
DATA_DIR.mkdir(exist_ok=True)
SENSE_FILE = DATA_DIR / "symbol_sense.json"


def _load_store() -> dict:
    if not SENSE_FILE.exists():
        return {}
    try:
        return json.loads(SENSE_FILE.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        return {}


def _save_store(store: dict) -> None:
    SENSE_FILE.write_text(json.dumps(store, indent=2, ensure_ascii=False), encoding="utf-8")


class SensePayload(BaseModel):
    name: str = Field(..., min_length=1)
    location: str = Field(..., min_length=1)
    soulPalace: str = Field(..., min_length=1)
    numbers: list[int] = Field(..., min_length=3, max_length=3)
    soulId: str = Field(..., min_length=16)
    reading: str = ""


class SenseSession(BaseModel):
    session_id: str
    soul_id: str
    name_hash: str
    location_hash: str
    palace: str
    numbers: list[int]
    reading: str
    created_at: str


def _name_hash(name: str) -> str:
    return hashlib.sha256(f"ez:name:{name.lower().strip()}".encode()).hexdigest()[:16]


def _location_hash(location: str) -> str:
    return hashlib.sha256(f"ez:loc:{location.lower().strip()}".encode()).hexdigest()[:16]


@router.post("/record", response_model=dict)
async def record_sense(payload: SensePayload):
    store = _load_store()
    session_id = hashlib.sha256(
        f"{payload.soulId}:{time.time()}".encode()
    ).hexdigest()[:16]

    record = {
        "session_id": session_id,
        "soul_id": payload.soulId,
        "name_hash": _name_hash(payload.name),
        "location_hash": _location_hash(payload.location),
        "palace": payload.soulPalace,
        "numbers": payload.numbers,
        "reading": payload.reading,
        "created_at": datetime.utcnow().isoformat() + "Z",
    }
    store[session_id] = record
    _save_store(store)

    return {
        "success": True,
        "session_id": session_id,
        "message": "Frequency recorded in the water realm.",
    }


@router.get("/session/{session_id}", response_model=SenseSession)
async def get_session(session_id: str):
    store = _load_store()
    record = store.get(session_id)
    if not record:
        raise HTTPException(status_code=404, detail="Session not found in Lulu's archive.")
    return SenseSession(**record)


@router.get("/soul/{soul_id}", response_model=list[SenseSession])
async def get_by_soul_id(soul_id: str):
    store = _load_store()
    results = [r for r in store.values() if r.get("soul_id") == soul_id]
    return [SenseSession(**r) for r in results]


class SymbolSensePlugin(Plugin):
    name = "symbol_sense"
    version = "1.0.0"
    description = "Records and retrieves EZ-Input symbol-sensing sessions."

    def register(self, app: Any) -> None:
        app.include_router(router)
