"""Mock CERT / abuse-API receiver for the hackathon demo.

Pretends to be CERT-Bund, MISP, URLhaus, and AbuseIPDB. Accepts JSON payloads,
returns a receipt id + status. Submissions are kept in memory AND mirrored to
data/mock_cert/<receipt_id>.json so the demo has an artifact trail.
"""

from __future__ import annotations

from datetime import datetime, timezone
from typing import Any, Dict, List
from uuid import uuid4

from fastapi import FastAPI
from pydantic import BaseModel, Field

from psyc import DATA_DIR, log


_log = log.get(__name__)

MOCK_LOG_DIR = DATA_DIR / "mock_cert"


class MockSubmission(BaseModel):
    receipt_id: str
    destination: str
    status: str
    received_at: datetime
    payload: Dict[str, Any] = Field(default_factory=dict)


_submissions: List[MockSubmission] = []


def _record(destination: str, status: str, payload: Dict[str, Any]) -> MockSubmission:
    sub = MockSubmission(
        receipt_id=f"MOCK-{uuid4().hex[:12].upper()}",
        destination=destination,
        status=status,
        received_at=datetime.now(timezone.utc),
        payload=payload,
    )
    _submissions.append(sub)
    MOCK_LOG_DIR.mkdir(parents=True, exist_ok=True)
    (MOCK_LOG_DIR / f"{sub.receipt_id}.json").write_text(sub.model_dump_json(indent=2))
    _log.info("mock_cert.received", destination=destination, receipt_id=sub.receipt_id, status=status)
    return sub


app = FastAPI(title="psyc mock-cert", version="0.1.0")


@app.post("/cert-bund/submit")
def submit_cert_bund(payload: Dict[str, Any]) -> Dict[str, Any]:
    sub = _record("CERT-Bund", "acknowledged", payload)
    return {"receipt_id": sub.receipt_id, "destination": sub.destination, "status": sub.status, "received_at": sub.received_at.isoformat()}


@app.post("/misp/event")
def submit_misp(payload: Dict[str, Any]) -> Dict[str, Any]:
    sub = _record("MISP-Community", "submitted", payload)
    return {"receipt_id": sub.receipt_id, "destination": sub.destination, "status": sub.status, "received_at": sub.received_at.isoformat()}


@app.post("/urlhaus/submit")
def submit_urlhaus(payload: Dict[str, Any]) -> Dict[str, Any]:
    sub = _record("URLhaus", "actioned", payload)
    return {"receipt_id": sub.receipt_id, "destination": sub.destination, "status": sub.status, "received_at": sub.received_at.isoformat()}


@app.post("/abuseipdb/report")
def submit_abuseipdb(payload: Dict[str, Any]) -> Dict[str, Any]:
    sub = _record("AbuseIPDB", "submitted", payload)
    return {"receipt_id": sub.receipt_id, "destination": sub.destination, "status": sub.status, "received_at": sub.received_at.isoformat()}


@app.post("/soar/enforce")
def soar_enforce(payload: Dict[str, Any]) -> Dict[str, Any]:
    """Mock enforcement sink — stands in for a firewall/DNS/SOAR webhook."""
    sub = _record(f"SOAR:{payload.get('action_type', 'action')}", "enforced", payload)
    return {"receipt_id": sub.receipt_id, "destination": sub.destination, "status": sub.status, "received_at": sub.received_at.isoformat()}


@app.get("/received")
def received() -> Dict[str, Any]:
    return {"count": len(_submissions), "submissions": [s.model_dump(mode="json") for s in _submissions]}


@app.get("/healthz")
def healthz() -> Dict[str, str]:
    return {"status": "ok", "received": str(len(_submissions))}
