import type { Assessment, Level } from "@/lib/report-types";

export type RiskLevel = "Low" | "Moderate" | "High" | "Severe";

export type MoldIssue = {
  id: string;
  name: string;
  scientific?: string;
  appearance: string;
  color: string;
  locations: string;
  moisture: string;
  healthRisks: string;
  treatment: string;
  risk: RiskLevel;
};

export type MoldSpecies = {
  id: string;
  name: string;
  appearance: string;
  locations: string;
  moistureSource: string;
  healthEffects: string;
  risk: RiskLevel;
  treatment: string;
};

export const MOLD_ISSUES: MoldIssue[] = [
  {
    id: "black-mold",
    name: "Black Mold",
    scientific: "Stachybotrys chartarum",
    appearance: "Dense slimy or sooty patches that spread outward from a wet seam or corner.",
    color: "Greenish-black to charcoal",
    locations: "Water-damaged drywall, ceiling boards, behind sinks, around burst pipes and roof leaks.",
    moisture: "Constant saturation for 7+ days, typically 90%+ material moisture.",
    healthRisks: "Coughing, wheezing, sinus irritation, headaches, fatigue; mycotoxin concerns with long exposure.",
    treatment: "Do not disturb it. Professional containment, removal of affected drywall, antimicrobial treatment and moisture repair.",
    risk: "Severe",
  },
  {
    id: "white-mold",
    name: "White Mold",
    appearance: "Powdery or cotton-like fuzz that wipes away but returns quickly.",
    color: "White to pale grey",
    locations: "Bathrooms, wardrobes, basements, timber joists, stored fabric and cardboard.",
    moisture: "High humidity (above 60% RH) and poor airflow rather than standing water.",
    healthRisks: "Allergy symptoms, sneezing, itchy eyes, skin irritation, asthma triggers.",
    treatment: "Clean with antimicrobial solution, dry the substrate, dehumidify and improve ventilation.",
    risk: "Moderate",
  },
  {
    id: "condensation-mold",
    name: "Condensation Mold",
    appearance: "Fine black speckles along window seals, sills and cold corners.",
    color: "Black, dark grey, sometimes pink-tinged",
    locations: "Window frames, glass seals, tiled corners, external wall corners, behind furniture.",
    moisture: "Warm humid air condensing on cold surfaces, worst overnight and in rainy season.",
    healthRisks: "Nasal congestion, sneezing, eye irritation, aggravated asthma.",
    treatment: "Wipe with mould-safe cleaner, ventilate daily, add insulation and reduce indoor humidity to 30–50%.",
    risk: "Low",
  },
  {
    id: "green-mold",
    name: "Organic Green Mold",
    appearance: "Fuzzy circular colonies on organic material such as food, paper and plaster.",
    color: "Olive, lime or blue-green",
    locations: "Damp cardboard, wallpaper, food stores, plaster ceilings, kitchen cabinets.",
    moisture: "Recurrent damp, spills, leaking appliances and poor drying.",
    healthRisks: "Allergic reactions, respiratory irritation, infections in vulnerable people.",
    treatment: "Discard porous items, disinfect surfaces, fix the water source and fumigate if widespread.",
    risk: "Moderate",
  },
];

export const MOLD_SPECIES: MoldSpecies[] = [
  {
    id: "cladosporium",
    name: "Cladosporium",
    appearance: "Olive-green, brown or black suede-like colonies.",
    locations: "Exterior walls, window frames, fabrics, carpets, HVAC ducts.",
    moistureSource: "Rain penetration through external walls and condensation.",
    healthEffects: "Asthma attacks, sinusitis, skin rashes, eye and throat irritation.",
    risk: "Moderate",
    treatment: "Surface remediation, external wall sealing and duct cleaning.",
  },
  {
    id: "penicillium",
    name: "Penicillium",
    appearance: "Blue-green velvety colonies with a white border.",
    locations: "Water-damaged carpet, wallpaper, insulation, mattresses, food.",
    moistureSource: "Flooding, plumbing leaks and prolonged damp.",
    healthEffects: "Allergies, chronic sinus inflammation, asthma triggers.",
    risk: "Moderate",
    treatment: "Removal of porous materials, HEPA cleaning and antimicrobial fogging.",
  },
  {
    id: "aspergillus",
    name: "Aspergillus",
    appearance: "Powdery colonies in yellow-green, grey or white with thick spore heads.",
    locations: "Air conditioning units, dusty surfaces, damp insulation, stored grain.",
    moistureSource: "Humidity above 60% and dust accumulation.",
    healthEffects: "Respiratory infection risk, aspergillosis in immunocompromised people, allergic reactions.",
    risk: "High",
    treatment: "Professional removal with containment, HVAC decontamination and humidity control.",
  },
  {
    id: "stachybotrys",
    name: "Stachybotrys chartarum",
    appearance: "Slimy dark greenish-black colonies with a wet sheen.",
    locations: "Chronically wet drywall, ceiling boards, wood and paper backing.",
    moistureSource: "Persistent leaks, flooding and unresolved roof failure.",
    healthEffects: "Coughing, chest tightness, headaches, fatigue; mycotoxin exposure concerns.",
    risk: "Severe",
    treatment: "Full containment, material removal, negative-air remediation and post-clearance verification.",
  },
  {
    id: "alternaria",
    name: "Alternaria",
    appearance: "Dark grey-brown woolly colonies with fine hairs.",
    locations: "Showers, tubs, under sinks, window sills, exterior damp walls.",
    moistureSource: "Splash water, condensation and rain ingress.",
    healthEffects: "Hay-fever style allergies, asthma escalation, upper respiratory irritation.",
    risk: "Moderate",
    treatment: "Antimicrobial cleaning, resealing wet areas and improving extraction.",
  },
];

export const HEALTH_RISKS = [
  {
    id: "respiratory",
    title: "Respiratory",
    items: ["Asthma flare-ups", "Bronchitis", "Persistent coughing", "Wheezing and chest tightness"],
  },
  {
    id: "allergic",
    title: "Allergic",
    items: ["Sneezing", "Itchy or watering eyes", "Skin irritation and rashes", "Nasal congestion"],
  },
  {
    id: "neurological",
    title: "Neurological",
    items: ["Headaches", "Dizziness", "Fatigue and poor concentration"],
  },
  {
    id: "toxic",
    title: "Toxic exposure",
    items: [
      "Mycotoxin concerns from Stachybotrys and Aspergillus",
      "Long-term exposure risks for children, elderly and asthmatic occupants",
      "Reduced immunity with prolonged residence in damp buildings",
    ],
  },
] as const;

export const HEALTH_DISCLAIMER =
  "Medical disclaimer: this information is general guidance only and is not medical advice, diagnosis or treatment. If you or an occupant experiences persistent respiratory, allergic or neurological symptoms, consult a qualified medical practitioner.";

export const PREVENTION_CHECKLIST = [
  "Maintain indoor humidity between 30% and 50%",
  "Improve ventilation in every damp-prone room",
  "Use bathroom and kitchen exhaust fans during and after use",
  "Repair roof leaks immediately",
  "Repair plumbing leaks immediately",
  "Dry wet materials within 24–48 hours",
  "Reduce condensation on windows and cold walls",
  "Improve insulation on cold external surfaces",
  "Increase natural airflow and sunlight into the property",
];

export const MAINTENANCE_REMINDERS = [
  { every: "Weekly", task: "Wipe window sills and shower seals, check for new speckling." },
  { every: "Monthly", task: "Inspect under sinks, behind appliances and around water tanks for damp." },
  { every: "Quarterly", task: "Clean extractor fans and AC filters, verify humidity readings." },
  { every: "Every 6 months", task: "Check roof, gutters and external wall render before and after rainy season." },
  { every: "Yearly", task: "Book a professional mold inspection and moisture survey." },
];

export const CALL_PROFESSIONAL = [
  "Visible mold covering more than about 1 square metre",
  "Mold returning within weeks of cleaning",
  "A musty smell with no visible source",
  "Black staining on drywall, ceilings or after flooding",
  "Occupants with asthma, allergies or weakened immunity",
  "Suspected hidden leaks, damp walls or cold spots",
];

/** Match educational content to what the AI detected. */
export function educationForAssessment(a?: Assessment | null): {
  issue: MoldIssue;
  species: MoldSpecies[];
  reason: string;
} {
  const text = [
    a?.verdict,
    a?.summary,
    a?.leakage?.verdict,
    ...(a?.factors ?? []),
    ...(a?.leakage?.signs ?? []),
    ...(a?.detections ?? []).map((d) => d.surface ?? ""),
    ...(a?.causes ?? []).map((c) => c.cause ?? ""),
    a?.conclusion?.location,
    a?.conclusion?.likelyCauses,
  ]
    .filter(Boolean)
    .join(" ")
    .toLowerCase();

  const has = (...keys: string[]) => keys.some((k) => text.includes(k));
  const byId = (id: string) => MOLD_ISSUES.find((m) => m.id === id)!;
  const sp = (...ids: string[]) => MOLD_SPECIES.filter((s) => ids.includes(s.id));

  if (has("drywall", "plasterboard", "flood", "water damage", "soaked", "ceiling board")) {
    return { issue: byId("black-mold"), species: sp("stachybotrys", "penicillium"), reason: "Wet drywall or water-damaged board was indicated." };
  }
  if (has("window", "condensation", "glass", "cold spot")) {
    return { issue: byId("condensation-mold"), species: sp("cladosporium", "alternaria"), reason: "Condensation on cold surfaces was indicated." };
  }
  if (has("bathroom", "shower", "tile", "grout", "sink", "toilet")) {
    return { issue: byId("white-mold"), species: sp("alternaria", "penicillium"), reason: "Bathroom or wet-room moisture was indicated." };
  }
  if (has("exterior", "external wall", "rain", "roof", "outside wall")) {
    return { issue: byId("green-mold"), species: sp("cladosporium", "alternaria"), reason: "Exterior wall moisture or rain ingress was indicated." };
  }

  const severity = String(a?.severity ?? "").toLowerCase();
  if (severity.includes("high")) {
    return { issue: byId("black-mold"), species: sp("stachybotrys", "aspergillus"), reason: "A high-severity result was returned." };
  }
  return { issue: byId("white-mold"), species: sp("penicillium", "cladosporium"), reason: "General damp and humidity conditions were indicated." };
}

export function riskTone(risk: RiskLevel | Level | string | undefined) {
  const v = String(risk ?? "").toLowerCase();
  if (v.includes("severe") || v.includes("high")) return "bg-destructive/10 text-destructive";
  if (v.includes("moderate") || v.includes("medium")) return "bg-accent/15 text-accent-foreground";
  return "bg-primary/10 text-primary";
}
