import urllib.request
import json
import os
import sys

base_url = "http://localhost:5179"
output_file = r"C:\Users\gulum\dev\GerbilManager\docs\active-triage-summary.md"

def fetch_json(path):
    url = f"{base_url}{path}"
    try:
        req = urllib.request.Request(url)
        with urllib.request.urlopen(req) as r:
            return json.loads(r.read().decode('utf-8'))
    except Exception:
        return None

def main():
    print("Fetching active tickets...")
    all_tickets = fetch_json("/feedback")
    if not all_tickets:
        print("Error: Could not retrieve tickets from API. Is the server running?")
        sys.exit(1)
        
    active_tickets = []
    for t in all_tickets:
        status = t.get("status")
        if status in ("Open", "Answered"):
            active_tickets.append(t)
        elif status == "NeedsInfo":
            thread = t.get("thread", [])
            if thread and thread[-1].get("role") == "breeder":
                active_tickets.append(t)
    print(f"Found {len(active_tickets)} active tickets.")
    
    markdown_content = []
    markdown_content.append("# Active Tickets Triage Summary")
    markdown_content.append(f"*Generated automatically on 2026-06-28. Total active: {len(active_tickets)}*\n")
    markdown_content.append("This file aggregates all active feedback tickets with their full database context and source provenance to allow quick resolution.\n")
    markdown_content.append("---")
    
    for idx, t in enumerate(active_tickets, 1):
        tid = t.get("id")
        status = t.get("status")
        msg = t.get("message") or "No message"
        category = t.get("category") or "General"
        entity_name = t.get("entityName") or "None"
        gerbil_id = t.get("gerbilId")
        litter_id = t.get("litterId")
        question = t.get("question")
        answer = t.get("answer")
        agent_context = t.get("agentContext")
        
        markdown_content.append(f"\n## {idx}. [{status}] Ticket `{tid[:8]}` (ID: `{tid}`)")
        markdown_content.append(f"- **Breeder's Message**: \"{msg.strip()}\"")
        markdown_content.append(f"- **Category**: `{category}` | **Target Name**: `{entity_name}`")
        
        # 1. Fetch Gerbil context if available
        if gerbil_id:
            g_data = fetch_json(f"/gerbils/{gerbil_id}")
            if g_data:
                markdown_content.append("\n### Target Gerbil Context:")
                markdown_content.append(f"- **Name**: `{g_data.get('name')}`")
                markdown_content.append(f"- **Gender**: `{g_data.get('gender')}` | **Status**: `{g_data.get('status')}`")
                markdown_content.append(f"- **DOB**: `{g_data.get('dateOfBirth') or 'None'}` | **DOD**: `{g_data.get('dateOfDeath') or 'None'}`")
                markdown_content.append(f"- **Genotype**: `{g_data.get('genotype') or 'None'}`")
                markdown_content.append(f"- **Notes**: `{g_data.get('notes') or 'None'}`")
                markdown_content.append(f"- **Import Source**: `{g_data.get('importSource')}`")
                markdown_content.append(f"- **ExternalRef**: `{g_data.get('externalRef')}`")
                
                # Format Provenance history nicely if present
                prov_str = g_data.get("provenance")
                if prov_str:
                    try:
                        prov = json.loads(prov_str)
                        markdown_content.append("- **Provenance History**:")
                        for entry in prov.get("history", []):
                            markdown_content.append(f"  - {entry}")
                    except Exception:
                        pass
            else:
                markdown_content.append(f"\n### Target Gerbil: `gerbils/{gerbil_id}` (Not found in active DB - Suppressed/Deleted)")
                
        # 2. Fetch Litter context if available
        if litter_id:
            l_data = fetch_json(f"/litters/{litter_id}")
            if l_data:
                markdown_content.append("\n### Target Litter Context:")
                markdown_content.append(f"- **Litter Name**: `{l_data.get('name')}`")
                markdown_content.append(f"- **Date**: `{l_data.get('date') or 'None'}` | **Total Born**: `{l_data.get('totalBorn') or 'None'}`")
                markdown_content.append(f"- **Father ID**: `{l_data.get('fatherId') or 'None'}` | **Mother ID**: `{l_data.get('motherId') or 'None'}`")
                markdown_content.append(f"- **Notes**: `{l_data.get('notes') or 'None'}`")
                markdown_content.append(f"- **ExternalRef**: `{l_data.get('externalRef')}`")
            else:
                markdown_content.append(f"\n### Target Litter: `litters/{litter_id}` (Not found in active DB - Suppressed/Deleted)")
                
        if question:
            markdown_content.append(f"\n### AI Question Asked:\n> {question.strip()}")
            
        if answer:
            markdown_content.append(f"\n### Breeder's Answer:\n> **{answer.strip()}**")
            
        if agent_context:
            markdown_content.append(f"\n### Internal Agent Context:\n```json\n{agent_context.strip()}\n```")
            
        markdown_content.append("\n### Triage Resolution Plan:")
        # Generate some smart heuristic recommendation based on breeder response
        if status == "Answered" and answer:
            ans_lower = answer.lower()
            if "verstorben" in ans_lower or ("gestorben" in ans_lower) or any(char.isdigit() for char in answer):
                markdown_content.append("- [ ] **Action**: Update status to `Deceased`, add `dateOfDeath`, and maybe Abnehmer/receiver.")
            elif "gleiche" in ans_lower or "selbe" in ans_lower:
                markdown_content.append("- [ ] **Action**: Merge duplicate records by setting `correctDob` or aligning names.")
            elif "vater" in ans_lower or "mutter" in ans_lower:
                markdown_content.append("- [ ] **Action**: Set parents (father/mother) or inject litter override.")
            else:
                markdown_content.append("- [ ] **Action**: Apply conflict-decision resolution based on response text.")
        else:
            markdown_content.append("- [ ] **Action**: Investigate original message and check database records for appropriate override.")
            
        markdown_content.append("\n---")
        
    os.makedirs(os.path.dirname(output_file), exist_ok=True)
    with open(output_file, "w", encoding="utf-8") as f:
        f.write("\n".join(markdown_content) + "\n")
        
    print(f"Triage report written to {output_file}")

if __name__ == "__main__":
    main()
