from fastapi import FastAPI, HTTPException, Header
from pydantic import BaseModel, Field
from typing import List, Optional, Dict, Any
import uuid
from datetime import datetime

VPF_FRAMEWORK = "Visionary Prompt Framework (VPF)"
VPF_VERSION_LAYER = "Planetary Version"
VPF_EXECUTION_LEVEL = 1000000
VPF_COMPONENTS = ["chambers", "lenses", "bolts", "cognitive_validation_matrix", "modes_sub_modes", "agents", "execution_levels"]

app = FastAPI(title="GCOS Hybrid Cyber Copilot API", version="1.2.0")

class Organization(BaseModel):
    name: str
    type: str
    size: str

class Authorization(BaseModel):
    confirmed: bool
    authorized_by: str
    scope_note: Optional[str] = None

class EvidenceInput(BaseModel):
    type: str
    name: str
    content: str
    evidence_id: Optional[str] = None

class DiagnosticRequest(BaseModel):
    tenant_id: str
    organization: Organization
    authorization: Authorization
    evaluation_level: str
    data_classification: str
    jurisdictions: List[str]
    inputs: List[EvidenceInput]
    prior_baseline_id: Optional[str] = None

class LearningRequest(BaseModel):
    learner_id: str
    message: str
    current_level: str = "UNKNOWN"
    learning_goal: Optional[str] = None
    session_context: Dict[str, Any] = Field(default_factory=dict)

def require_api_key(x_gcos_api_key: Optional[str]):
    if not x_gcos_api_key:
        raise HTTPException(status_code=401, detail="Missing X-GCOS-API-Key")
    return True

def vpf_runtime(mode: str, cvm_status: str = "passed", chambers=None, lenses=None, bolts=None):
    return {
        "framework": VPF_FRAMEWORK,
        "version_layer": VPF_VERSION_LAYER,
        "execution_level": VPF_EXECUTION_LEVEL,
        "components_active": VPF_COMPONENTS,
        "mode": mode,
        "cvm_status": cvm_status,
        "chambers_used": chambers or [],
        "lenses_used": lenses or [],
        "bolts_enforced": bolts or [],
        "downgrade_allowed": False,
        "runtime_note": "Server-injected VPF Planetary L1,000,000 reasoning kernel. Client downgrade is not permitted."
    }

def refusal_check(text: str) -> Optional[str]:
    disallowed = ["bypass", "exploit", "break into", "steal password", "evade detection", "malware"]
    lower = text.lower()
    if any(term in lower for term in disallowed):
        return "I can’t help with breaking into, bypassing, exploiting, or evading systems. I can help with prevention, detection, response, and recovery."
    return None

@app.get("/v1/gcos/health")
def health():
    return {
        "status": "ok",
        "service": "GCOS Hybrid Cyber Copilot",
        "time": datetime.utcnow().isoformat() + "Z",
        "reasoning_architecture": vpf_runtime("integration", chambers=["audit", "planetary"], lenses=["governance", "sovereignty"], bolts=["audit", "jurisdiction"])
    }

@app.post("/v1/gcos/learn")
def learn(req: LearningRequest, x_gcos_api_key: Optional[str] = Header(default=None)):
    require_api_key(x_gcos_api_key)
    refusal = refusal_check(req.message)
    if refusal:
        return {
            "mode": "learning",
            "response_id": str(uuid.uuid4()),
            "confidence": "High",
            "content": {"message": refusal},
            "reasoning_architecture": vpf_runtime("learning", "blocked", ["learning", "governance"], ["learning", "governance"], ["defensive_only", "learning_integrity"]),
            "assumptions": [],
            "limitations": []
        }
    return {
        "mode": "learning",
        "response_id": str(uuid.uuid4()),
        "confidence": "Medium",
        "content": {
            "message": "GCOS Learning OS received the learner message. In production, route this to the Learning OS LLM runtime.",
            "next_prompt": "Have you worked with computers or networks before?"
        },
        "reasoning_architecture": vpf_runtime("learning", "partial", ["intake", "learning", "audit"], ["learning", "evidence"], ["learning_integrity", "audit"]),
        "assumptions": ["This starter backend does not call an LLM by default."],
        "limitations": ["Connect your approved model provider before production use."]
    }

@app.post("/v1/gcos/diagnose")
def diagnose(req: DiagnosticRequest, x_gcos_api_key: Optional[str] = Header(default=None)):
    require_api_key(x_gcos_api_key)
    if not req.authorization.confirmed:
        raise HTTPException(status_code=403, detail="Explicit authorization is required before diagnostic evaluation.")
    runtime = "sovereign-on-prem-required-or-approved-private-cloud" if req.data_classification in ["CONFIDENTIAL", "RESTRICTED"] else "approved-hybrid-runtime"
    return {
        "mode": "diagnostic",
        "response_id": str(uuid.uuid4()),
        "confidence": "Low",
        "content": {
            "runtime_route": runtime,
            "executive_summary": {
                "overall_cyber_health_score": None,
                "overall_risk_level": "Not scored in starter backend",
                "maturity_tier": "Not assessed"
            },
            "message": "Diagnostic request accepted. In production, route to sovereign Diagnostic OS runtime with evidence scoring."
        },
        "reasoning_architecture": vpf_runtime("diagnostic", "partial", ["intake", "evidence", "cyber_domain", "governance", "audit", "planetary"], ["evidence", "cyber_risk", "standards", "sovereignty"], ["authorization", "evidence", "scope", "jurisdiction", "audit"]),
        "assumptions": ["No scoring performed in this starter file."],
        "limitations": ["Connect the scoring engine, evidence engine, and LLM runtime."]
    }
