# main.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field, EmailStr, conint, validator
from typing import List, Optional, Dict
from datetime import date
import re
import uuid

app = FastAPI(title="Insurance API")

# ----------------------
# Helpers / In-memory DB
# ----------------------
def _gen_id() -> str:
    return uuid.uuid4().hex

def _mask_email(email: str) -> str:
    # simple mask: first char + *** + domain
    local, domain = email.split("@", 1)
    return (local[:1] + "***@" + domain)

def _mask_phone(phone: str) -> str:
    # keep last 4
    digits = re.sub(r"\D", "", phone)
    return "***-***-" + digits[-4:] if len(digits) >= 4 else "***"

PHONE_REGEX = r"^\(\d{3}\)\s?\d{3}-\d{4}$"

db_agri: Dict[str, dict] = {}
db_bop: Dict[str, dict]  = {}
db_health: Dict[str, dict] = {}

# -------------
# Schemas
# -------------
class AgricultureCreate(BaseModel):
    full_name: str
    entity_type: str
    email_address: EmailStr
    phone_number: str = Field(..., pattern=PHONE_REGEX)
    state: str
    zip_code: str
    farm_name: str
    total_acres_owned: int
    farm_type: List[str]
    annual_revenue: float
    perils_to_cover: List[str]
    preferred_contact_method: str

class AgricultureOut(AgricultureCreate):
    id: str
    quote_status: str
    masked_email: str
    masked_phone: str

class BOPCreate(BaseModel):
    business_name: str
    contact_name: str
    email_address: EmailStr
    phone_number: str = Field(..., pattern=PHONE_REGEX)
    business_address: str
    type_of_business: str
    years_in_business: int
    annual_revenue: float
    number_of_employees: conint(ge=1)
    property_owned_or_leased: str
    property_addresses: List[str]
    square_footage: int
    building_construction_type: str
    year_built: int
    business_personal_property_value: float
    building_value: float
    prior_claims_last_5_years: bool
    description_of_past_claims: Optional[str] = None
    desired_coverage_start_date: date
    desired_property_coverage_limit: float
    desired_general_liability_coverage_limit: float
    security_safety_features: List[str]

class BOPOut(BOPCreate):
    id: str
    quote_status: str

class HealthDependent(BaseModel):
    name: str
    date_of_birth: date
    gender: str
    relationship: str

class HealthCreate(BaseModel):
    full_name: str
    date_of_birth: date
    gender: str
    email: EmailStr
    phone_number: str = Field(..., pattern=PHONE_REGEX)
    residential_address: str
    zip_code: str
    tobacco_usage: bool
    household_size: conint(ge=1)
    add_dependents: bool
    dependent_info: Optional[List[HealthDependent]] = None
    coverage_start_date: date
    consent_to_share: bool

    @validator("dependent_info", always=True)
    def validate_dependents(cls, v, values):
        if values.get("add_dependents") and not v:
            raise ValueError("dependent_info required when add_dependents is True")
        return v

class HealthOut(HealthCreate):
    id: str
    quote_status: str
    masked_email: str

# -------------
# Health checks
# -------------
@app.get("/health")
def health():
    return {"status": "healthy"}

# ----------------------------
# Agriculture Insurance routes
# ----------------------------
@app.post("/agriculture-insurance/", response_model=AgricultureOut)
def create_agriculture(payload: AgricultureCreate):
    _id = _gen_id()
    rec = payload.dict()
    rec.update({
        "id": _id,
        "quote_status": "Draft",
        "masked_email": _mask_email(payload.email_address),
        "masked_phone": _mask_phone(payload.phone_number),
    })
    db_agri[_id] = rec
    return rec

@app.get("/agriculture-insurance/", response_model=List[AgricultureOut])
def list_agriculture():
    return list(db_agri.values())

@app.get("/agriculture-insurance/{item_id}", response_model=AgricultureOut)
def get_agriculture(item_id: str):
    rec = db_agri.get(item_id)
    if not rec:
        raise HTTPException(status_code=404, detail="Not found")
    return rec

@app.put("/agriculture-insurance/{item_id}", response_model=AgricultureOut)
def update_agriculture(item_id: str, payload: dict):
    rec = db_agri.get(item_id)
    if not rec:
        raise HTTPException(status_code=404, detail="Not found")
    # allow partial updates for tests
    rec.update(payload)
    db_agri[item_id] = rec
    return rec

@app.delete("/agriculture-insurance/{item_id}")
def delete_agriculture(item_id: str):
    if item_id in db_agri:
        del db_agri[item_id]
        return {"deleted": True}
    raise HTTPException(status_code=404, detail="Not found")

# ----------------------------
# Business Owner Policy routes
# ----------------------------
@app.post("/business-owner-policy/", response_model=BOPOut)
def create_bop(payload: BOPCreate):
    _id = _gen_id()
    rec = payload.dict()
    rec.update({"id": _id, "quote_status": "Draft"})
    db_bop[_id] = rec
    return rec

@app.get("/business-owner-policy/", response_model=List[BOPOut])
def list_bop():
    return list(db_bop.values())

@app.get("/business-owner-policy/{item_id}", response_model=BOPOut)
def get_bop(item_id: str):
    rec = db_bop.get(item_id)
    if not rec:
        raise HTTPException(status_code=404, detail="Not found")
    return rec

@app.put("/business-owner-policy/{item_id}", response_model=BOPOut)
def update_bop(item_id: str, payload: dict):
    rec = db_bop.get(item_id)
    if not rec:
        raise HTTPException(status_code=404, detail="Not found")
    rec.update(payload)
    db_bop[item_id] = rec
    return rec

@app.delete("/business-owner-policy/{item_id}")
def delete_bop(item_id: str):
    if item_id in db_bop:
        del db_bop[item_id]
        return {"deleted": True}
    raise HTTPException(status_code=404, detail="Not found")

# ----------------------------
# Health Insurance routes
# ----------------------------
@app.post("/health-insurance/", response_model=HealthOut)
def create_health(payload: HealthCreate):
    _id = _gen_id()
    rec = payload.dict()
    rec.update({
        "id": _id,
        "quote_status": "Draft",
        "masked_email": _mask_email(payload.email),
    })
    db_health[_id] = rec
    return rec

@app.get("/health-insurance/", response_model=List[HealthOut])
def list_health():
    return list(db_health.values())

@app.get("/health-insurance/{item_id}", response_model=HealthOut)
def get_health(item_id: str):
    rec = db_health.get(item_id)
    if not rec:
        raise HTTPException(status_code=404, detail="Not found")
    return rec

@app.put("/health-insurance/{item_id}", response_model=HealthOut)
def update_health(item_id: str, payload: dict):
    rec = db_health.get(item_id)
    if not rec:
        raise HTTPException(status_code=404, detail="Not found")
    rec.update(payload)
    db_health[item_id] = rec
    return rec

@app.delete("/health-insurance/{item_id}")
def delete_health(item_id: str):
    if item_id in db_health:
        del db_health[item_id]
        return {"deleted": True}
    raise HTTPException(status_code=404, detail="Not found")
