"""
Seed script: inserts fake clients, projects, tasks, timeline events, and notes
into the local adiuvAI SQLite database.

Usage:  python scripts/seed-fake-data.py
"""

import os
import sqlite3
import uuid
import random
import time

# ── locate the database ──────────────────────────────────────────────────
appdata = os.environ.get("APPDATA")
if not appdata:
    raise RuntimeError("APPDATA environment variable not found (Windows only)")
db_path = os.path.join(appdata, "adiuvAI", "adiuvai.db")

if not os.path.isfile(db_path):
    raise FileNotFoundError(f"Database not found at {db_path}. Is the app installed / run at least once?")

print(f"Using database: {db_path}")

conn = sqlite3.connect(db_path)
cur = conn.cursor()

# ── helpers ───────────────────────────────────────────────────────────────
def uid():
    return str(uuid.uuid4())

def ts(days_ago=0):
    """Timestamp in ms, optionally shifted into the past."""
    return int((time.time() - days_ago * 86400) * 1000)

# ── fake data definitions ────────────────────────────────────────────────
CLIENTS = [
    {"name": "Acme Corp",        "industry": "Manufacturing"},
    {"name": "Globex Inc",       "industry": "Technology"},
    {"name": "Initech Solutions", "industry": "Finance"},
    {"name": "Umbrella Labs",    "industry": "Healthcare"},
    {"name": "Wayne Enterprises", "industry": "Defense & Engineering"},
]

PROJECTS_PER_CLIENT = [
    # (name, status)
    [("Website Redesign", "active"), ("ERP Migration", "active")],
    [("AI Chatbot MVP", "active"), ("Cloud Infrastructure", "archived")],
    [("Compliance Audit Tool", "active"),],
    [("Patient Portal v2", "active"), ("Lab Inventory System", "active"), ("R&D Dashboard", "archived")],
    [("Bat-Signal Network", "active"), ("Vehicle Fleet Tracker", "active")],
]

TASK_TEMPLATES = [
    ("Design homepage mockup",        "Create wireframes and high-fidelity mockups for the landing page",  "todo",        "high"),
    ("Set up CI/CD pipeline",         "Configure GitHub Actions with build, test, deploy stages",          "in-progress", "high"),
    ("Write unit tests for auth",     "Cover login, register, and token refresh flows",                    "todo",        "medium"),
    ("Database schema review",        "Review ERD and optimize indexes for production workload",           "done",        "medium"),
    ("Implement search feature",      "Full-text search across projects and notes",                        "todo",        "low"),
    ("Fix timezone bug",              "Date picker shows wrong day for UTC+offset users",                  "in-progress", "high"),
    ("API rate limiting",             "Add sliding-window rate limiter to public endpoints",               "todo",        "medium"),
    ("Onboarding walkthrough",        "Build step-by-step tour for new users",                             "todo",        "low"),
    ("Performance profiling",         "Identify and fix top 3 slow queries",                               "done",        "high"),
    ("Accessibility audit",           "Ensure WCAG 2.1 AA compliance across all pages",                    "todo",        "medium"),
    ("Mobile responsive layout",      "Adapt dashboard for tablets and phones",                            "in-progress", "medium"),
    ("Export to PDF",                 "Allow users to export reports and invoices to PDF",                  "todo",        "low"),
]

TIMELINE_TEMPLATES = [
    ("Project Kickoff",         0,  None),
    ("Design Phase Complete",   14, None),
    ("Alpha Release",           30, None),
    ("Beta Testing",            45, 60),
    ("User Acceptance Testing", 60, 75),
    ("Production Launch",       90, None),
    ("Post-Launch Review",      100, None),
]

NOTE_TEMPLATES = [
    ("Meeting Notes — Kickoff",
     "## Attendees\n- Product Owner\n- Dev Lead\n- Designer\n\n## Key Decisions\n1. Use React + TypeScript stack\n2. Two-week sprint cycles\n3. MVP scope: auth, dashboard, CRUD\n\n## Action Items\n- [ ] Set up repo\n- [ ] Create Figma workspace\n- [ ] Schedule daily standups"),

    ("Architecture Decision Record",
     "## ADR-001: Database Choice\n\n**Status:** Accepted\n\n**Context:** Need a lightweight, embedded database for local-first architecture.\n\n**Decision:** SQLite with WAL mode via better-sqlite3.\n\n**Consequences:**\n- Fast reads, good enough writes\n- No external service dependency\n- Limited concurrent write throughput (acceptable for single-user app)"),

    ("Sprint Retrospective",
     "## What went well\n- Shipped auth flow ahead of schedule\n- Good collaboration between design and dev\n\n## What could improve\n- Too many context switches mid-sprint\n- Need clearer acceptance criteria on tickets\n\n## Actions\n- Tech lead to review tickets before sprint start\n- Block Friday afternoons for deep work"),

    ("Research: API Integrations",
     "## Potential Integrations\n\n### Stripe\n- Webhooks for subscription events\n- Customer portal for self-service\n\n### SendGrid\n- Transactional emails (welcome, reset password)\n- Monthly digest newsletter\n\n### Sentry\n- Error tracking in production\n- Performance monitoring\n\n**Next step:** Create proof-of-concept for Stripe integration"),
]

# ── insert data ───────────────────────────────────────────────────────────
client_ids = []
project_ids = []

print("\n── Creating clients ──")
for i, c in enumerate(CLIENTS):
    cid = uid()
    client_ids.append(cid)
    cur.execute(
        "INSERT INTO clients (id, parent_id, name, industry, created_at) VALUES (?, ?, ?, ?, ?)",
        (cid, None, c["name"], c["industry"], ts(random.randint(60, 180)))
    )
    print(f"  ✓ {c['name']}")

print("\n── Creating projects ──")
for i, proj_list in enumerate(PROJECTS_PER_CLIENT):
    for pname, pstatus in proj_list:
        pid = uid()
        project_ids.append((pid, client_ids[i]))
        cur.execute(
            "INSERT INTO projects (id, client_id, name, status, ai_summary, created_at) VALUES (?, ?, ?, ?, ?, ?)",
            (pid, client_ids[i], pname, pstatus, None, ts(random.randint(30, 90)))
        )
        print(f"  ✓ {pname} → {CLIENTS[i]['name']}")

print("\n── Creating tasks ──")
task_count = 0
for pid, _cid in project_ids:
    # 3-5 random tasks per project
    selected = random.sample(TASK_TEMPLATES, k=random.randint(3, 5))
    for title, desc, status, priority in selected:
        tid = uid()
        due = ts(-random.randint(5, 45))  # future dates
        cur.execute(
            "INSERT INTO tasks (id, project_id, title, description, status, priority, assignee, due_date, is_ai_suggested, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
            (tid, pid, title, desc, status, priority, random.choice(["Alice", "Bob", "Carol", None]),
             due, 0, ts(random.randint(1, 30)))
        )
        task_count += 1
print(f"  ✓ {task_count} tasks created across {len(project_ids)} projects")

print("\n── Creating timeline events ──")
event_count = 0
for pid, _cid in project_ids:
    base_days_ago = random.randint(10, 60)
    for title, offset, end_offset in TIMELINE_TEMPLATES:
        eid = uid()
        event_date = ts(base_days_ago - offset)  # spread into future
        end_date = ts(base_days_ago - end_offset) if end_offset else None
        is_completed = 1 if offset < 20 else 0
        cur.execute(
            "INSERT INTO timeline_events (id, project_id, title, date, end_date, is_completed, is_ai_suggested, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
            (eid, pid, title, event_date, end_date, is_completed, 0, ts(random.randint(10, 60)))
        )
        event_count += 1
print(f"  ✓ {event_count} timeline events created")

print("\n── Creating notes ──")
note_count = 0
for pid, _cid in project_ids:
    # 1-3 notes per project
    selected = random.sample(NOTE_TEMPLATES, k=random.randint(1, 3))
    for title, content in selected:
        nid = uid()
        created = ts(random.randint(1, 30))
        cur.execute(
            "INSERT INTO notes (id, project_id, title, content, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)",
            (nid, pid, title, content, created, created)
        )
        note_count += 1
print(f"  ✓ {note_count} notes created")

# ── commit & close ────────────────────────────────────────────────────────
conn.commit()
conn.close()

print(f"""
═══════════════════════════════════════
  Seed complete!
  {len(CLIENTS)} clients
  {len(project_ids)} projects
  {task_count} tasks
  {event_count} timeline events
  {note_count} notes
═══════════════════════════════════════
  Restart adiuvAI to see the data.
""")
