"""
Gremlin impact reporting and stats tracking.
"""

from __future__ import annotations

import json
import random
import sys
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List

STATS_FILE = Path(".g_gremlin/stats.json")

TIME_ESTIMATES = {
    "formula_fix": 2,  # minutes per formula fix
    "formula_inspect": 0.1,  # minutes per formula inspected
    "cross_sheet_ref": 1,  # minutes to preserve a ref
    "backup_value": 5,  # minutes to copy a tab
    "lag_formula": 1,  # minutes to write an OFFSET
}

MESSAGES = {
    "lint_clean": [
        "Sniffed {count} formulas. Squeaky clean. The gremlin is impressed. (Suspicious, even.)",
        "Zero issues in {count} formulas. Either you're good, or I'm slipping.",
        "{count} formulas checked. Nothing to fix. The gremlin is... bored.",
        "Gremlin triple-checked {count} formulas. Not even sweating. Victory lap?",
        "Checked {count} formulas. Sales will say they 'had a feeling' it was fine. Sure.",
        "{count} formulas and not a single #REF. Did sales actually QA this? Kidding.",
        "All {count} formulas clean. Someone tell the AE this is what 'pipeline hygiene' looks like.",
        "No issues in {count} formulas. The forecast might actually be accurate. (Don't quote me.)",
        "{count} formulas validated. Cleaner than a freshly scrubbed CRM. Rare.",
        "Zero problems. {count} formulas. Either RevOps is on point or sales hasn't touched it yet.",
    ],
    "lint_found": [
        "Sniffed {count} formulas. Found {issues} gremlins hiding in there.",
        "Checked {count} formulas. {issues} of them were up to no good.",
        "{issues} problems lurking in {count} formulas. Someone's been sloppy...",
        "Found {issues} gremlins in {count} formulas. Hazard pay approved.",
        "{issues} issues in {count} formulas. Lemme guess, the 'CSV from sales' came on a USB stick?",
        "{issues} broken refs in {count} formulas. Classic end-of-quarter energy.",
        "Detected {issues} issues. This has 'quick fix before the forecast call' written all over it.",
        "{issues} problems found. Someone copied this from last quarter and hoped for the best.",
        "Found {issues} issues in {count} formulas. Sales said it was 'mostly done'. It was not.",
        "{issues} gremlins lurking. This spreadsheet has been through some pipeline reviews.",
    ],
    "lint_fixed": [
        "Fixed {fixed} broken references. The other {remaining} are above my pay grade.",
        "Squashed {fixed} bugs. {remaining} need manual attention. I'm not a miracle worker.",
        "{fixed} formulas repaired. You almost broke everything. You're welcome.",
        "Patched {fixed} messes. {remaining} left so you still feel involved.",
        "{fixed} fixes shipped. {remaining} left so sales has something to blame.",
        "Auto-fixed {fixed}. {remaining} require human judgment. (RevOps, you're up.)",
        "{fixed} formulas corrected. {remaining} left—probably from that 'quick update' last Thursday.",
        "Repaired {fixed}. {remaining} still broken. Tell the AE their 'minor edit' wasn't minor.",
        "{fixed} down, {remaining} to go. The gremlin works faster than your deal desk.",
        "Fixed {fixed} refs. {remaining} remaining. Someone owes the gremlin a commission.",
    ],
    "validate_clean": [
        "{count} formulas, {refs} cross-sheet refs, zero problems. Ready to fly.",
        "Pre-flight complete. {count} formulas checked. All systems go.",
        "This CSV is clean. {count} formulas, no issues. The gremlin approves.",
        "The gremlin salutes you: {count} formulas pass inspection. Carry on.",
        "Validation clean. Sales can keep their 'intuition'; we have {count} receipts.",
        "{count} formulas validated. Ship it before someone adds 'one small change'.",
        "All {count} formulas check out. Cleaner than a new rep's pipeline.",
        "Pre-push validation passed. {count} formulas, zero drama. Unlike the forecast call.",
        "{count} formulas ready. This is what happens when RevOps reviews before sales 'helps'.",
        "Validated {count} formulas. Green across the board. Frame this moment.",
    ],
    "validate_caught": [
        "Caught {issues} bad refs BEFORE you pushed. You almost broke production.",
        "{issues} issues caught. This is why you have a gremlin.",
        "Intercepted {issues} disasters. The gremlin just saved your weekend.",
        "{issues} landmines defused. Tell sales they owe you coffee, not USB drives.",
        "Blocked {issues} problems from going live. You're welcome, pipeline.",
        "{issues} issues stopped at the gate. The gremlin doesn't let broken formulas ship.",
        "Caught {issues} errors. This is why we validate before the board deck goes out.",
        "{issues} problems intercepted. Someone almost sent this to the CFO. Yikes.",
        "Validation caught {issues} issues. The forecast lives another day.",
        "{issues} bad refs blocked. Tell the AE their 'final version' needed more work.",
    ],
    "bands_clean": [
        "{count} formulas verified. FY26 refs FY26, FY27 refs FY27. No time-travel bugs.",
        "Column bands check out. {count} formulas pointing at the right tabs.",
        "All {count} formulas in the right lanes. The gremlin is satisfied.",
        "Timeline intact. {count} formulas behaving. Gremlin prevented a time paradox.",
        "Banding aligned. {count} formulas on the right year. Sales can't time-travel their forecast anymore.",
        "{count} formulas checked. No fiscal year mix-ups. Finance can relax.",
        "FY banding verified. {count} formulas pointing at the correct periods. Order restored.",
        "All {count} formulas in their proper fiscal lanes. No accidental Q4-to-Q1 time warps.",
        "{count} formulas validated. The forecast doesn't think it's 2019 anymore.",
        "Banding clean. {count} formulas aligned. Tell finance this one's actually accurate.",
    ],
    "bands_mismatch": [
        "Found {mismatches} formulas pointing at the wrong year. Time paradox averted.",
        "{mismatches} mismatches! Someone mixed up their fiscal years.",
        "Column band check failed. {mismatches} formulas need fixing.",
        "Time cops alerted: {mismatches} band mismatches quarantined by the gremlin.",
        "{mismatches} fiscal faceplants. Tell finance it was like this when we found it.",
        "{mismatches} formulas looking at the wrong FY. Classic copy-paste from last year.",
        "Caught {mismatches} time-traveling refs. Someone's forecast was living in the past.",
        "{mismatches} band errors. This is what happens when you clone last year's model at midnight.",
        "Found {mismatches} FY mismatches. The board would've loved those 'projections'.",
        "{mismatches} formulas referencing the wrong period. RevOps needs coffee. And maybe a hug.",
    ],
    "write_complete": [
        "Wrote {formulas} formulas. Created a backup because gremlins don't trust anyone.",
        "{rows} rows written, {formulas} formulas live. Backup saved. Sleep well.",
        "Model deployed. {formulas} formulas, backup in place. The gremlin delivers.",
        "{rows} rows, {formulas} formulas shipped. Backup stashed. The gremlin drops the mic.",
        "Shipped {rows} rows/{formulas} formulas. Backup made. If sales breaks it, we roll back and laugh.",
        "{formulas} formulas deployed. Backup created. The gremlin always has a Plan B.",
        "Pushed {rows} rows, {formulas} formulas. Backup ready for when someone 'improves' it.",
        "{formulas} formulas live. Backup saved. Go ahead, let the AEs 'take a look'.",
        "Model shipped. {formulas} formulas in prod. Backup waiting for the inevitable Slack panic.",
        "{rows} rows deployed. {formulas} formulas. The gremlin delivered. Sales can take credit.",
    ],
    "copy_tab": [
        "Copied the tab and kept {refs} cross-sheet refs intact. Delete/recreate would've nuked them.",
        "Tab duplicated with {refs} references preserved. You're welcome.",
        "Safe copy complete. {refs} cross-sheet refs still working. The gremlin way.",
        "Duped tab, {refs} refs safe. Gremlin flexed and left the building.",
        "Copied tab; {refs} refs survived. Tell RevOps we didn't nuke their VLOOKUPs.",
        "Tab cloned. {refs} cross-sheet refs intact. That's how professionals do it.",
        "Duplicated with {refs} refs preserved. Unlike that time someone just deleted and recreated.",
        "{refs} references survived the copy. The gremlin respects the VLOOKUP.",
        "Safe copy done. {refs} refs still working. Tell the intern this is the way.",
        "Tab copied. {refs} refs preserved. The pipeline report lives to see another quarter.",
    ],
    "generate_lag": [
        "Generated {count} OFFSET formulas in {time}s. That's {saved} minutes saved.",
        "{count} lag formulas created instantly. Manual would've taken {saved} minutes.",
        "Lag row done. {count} formulas, {time} seconds. The gremlin is fast.",
        "Lag magic: {count} offsets in {time}s. Gremlin hands are a blur.",
        "Built {count} lag formulas in {time}s. Sales will still say 'can we have it live?'",
        "{count} OFFSET formulas generated. Faster than an AE updating their forecast.",
        "Lag formulas done. {count} in {time}s. You'd still be typing the first one.",
        "{count} lag formulas shipped in {time}s. The gremlin is basically a macro with attitude.",
        "Generated {count} offsets. {saved} minutes saved. Go take a coffee break.",
        "{count} formulas in {time}s. Tell sales this is why 'just add a row' isn't simple.",
    ],
    "repair_analyze": [
        "Found {issues} problems. Someone's been careless.",
        "{issues} issues detected. This spreadsheet has seen some things.",
        "Yikes. {issues} problems. Let's fix this mess.",
        "{issues} crimes spotted. Gremlin putting on the rubber gloves.",
        "{issues} crimes detected. Feels like a deck built at 2am before QBR.",
        "{issues} issues found. This model has been through some pipeline reviews.",
        "Detected {issues} problems. Someone's been 'iterating' without testing.",
        "{issues} errors spotted. Classic signs of a Friday afternoon forecast update.",
        "Found {issues} issues. This spreadsheet has more red flags than a bad deal.",
        "{issues} problems identified. The gremlin has seen worse. Barely.",
    ],
    "repair_fix_auto": [
        "Applied {fixed} high-confidence fixes. The rest need a human touch.",
        "{fixed} fixes shipped automatically. {remaining} left for review.",
        "Auto-repair done. {fixed} fixed, {remaining} skipped.",
        "Gremlin patched {fixed}. {remaining} left so you feel useful.",
        "Auto-fixed {fixed}. {remaining} waiting so RevOps thinks they're involved.",
        "{fixed} repairs auto-applied. {remaining} need human judgment. Tag, you're it.",
        "Fixed {fixed} automatically. {remaining} require someone who knows the business logic.",
        "{fixed} issues resolved. {remaining} parked. The gremlin knows its limits.",
        "Auto-repaired {fixed}. {remaining} left for the humans. Collaboration.",
        "{fixed} down, {remaining} flagged. The gremlin did the heavy lifting.",
    ],
    "repair_fix_manual": [
        "Fixed {fixed} issues with your approval. {remaining} remaining.",
        "{fixed} fixes applied. {remaining} still look suspicious.",
        "Gremlin + human teamed up: {fixed} fixed, {remaining} to go.",
        "Tag-teamed {fixed} fixes. {remaining} waiting for your signature.",
        "{fixed} fixes landed. {remaining} parked. Gremlin left a note: 'next time, buy espresso.'",
        "Applied {fixed} with your blessing. {remaining} still need attention.",
        "{fixed} repairs done together. {remaining} remaining. Good teamwork.",
        "Human-approved fixes: {fixed}. Outstanding: {remaining}. We make a good team.",
        "{fixed} fixed with your sign-off. {remaining} to review. The gremlin respects process.",
        "Collaborative repair: {fixed} done, {remaining} pending. RevOps and gremlin, unstoppable.",
    ],
    "repair_stub": [
        "Created {created} stub sheets with {values} inferred values. Review them!",
        "Stubbed {created} tabs so references stop breaking. Check the defaults.",
        "Placeholder sheets ready. {values} values prefilled; tweak as needed.",
        "Gremlin scaffolded {created} stubs with {values} guesses. Edit before bragging.",
        "Stubbed {created} tabs with {values} guesses. Tell sales 'it's a preview', they'll love that.",
        "{created} stub tabs created. {values} values seeded. Review before the forecast call.",
        "Scaffolded {created} sheets. {values} placeholders filled. The gremlin guessed conservatively.",
        "{created} stubs ready. {values} defaults in place. Tweak them before finance asks questions.",
        "Created {created} placeholder tabs. {values} values prefilled. Better than #REF errors everywhere.",
        "Stub sheets deployed: {created} tabs, {values} values. The gremlin bought you time.",
    ],
}

ACHIEVEMENTS = {
    "fixer_upper": {"name": "Fixer Upper", "emoji": "🔧", "desc": "Fixed 50+ formula issues", "threshold": 50, "stat": "issues_fixed"},
    "guardian_angel": {"name": "Guardian Angel", "emoji": "🛡️", "desc": "Caught errors before write", "threshold": 1, "stat": "disasters_prevented"},
    "reference_keeper": {"name": "Reference Keeper", "emoji": "📋", "desc": "Preserved 100+ cross-sheet refs", "threshold": 100, "stat": "cross_sheet_refs_preserved"},
    "speed_demon": {"name": "Speed Demon", "emoji": "⚡", "desc": "Generated 10+ lag formulas", "threshold": 10, "stat": "lag_formulas_generated"},
    "inspector": {"name": "Inspector Gremlin", "emoji": "🔍", "desc": "Inspected 1000+ formulas", "threshold": 1000, "stat": "formulas_inspected"},
    "backup_king": {"name": "Backup Royalty", "emoji": "💾", "desc": "Created 10+ backups", "threshold": 10, "stat": "backups_created"},
}


def get_gremlin_message(scenario: str, **kwargs: Any) -> str:
    templates = MESSAGES.get(scenario, ["The gremlin did something."])
    template = random.choice(templates)
    try:
        return template.format(**kwargs)
    except Exception:
        return template


def calculate_time_saved(stats: Dict[str, Any]) -> int:
    total = 0
    total += int(stats.get("issues_fixed", 0)) * TIME_ESTIMATES["formula_fix"]
    total += int(stats.get("formulas_inspected", 0) or stats.get("formulas_sniffed", 0)) * TIME_ESTIMATES["formula_inspect"]
    total += int(stats.get("cross_sheet_refs_preserved", 0)) * TIME_ESTIMATES["cross_sheet_ref"]
    total += int(stats.get("backups_created", 0)) * TIME_ESTIMATES["backup_value"]
    total += int(stats.get("lag_formulas_generated", 0)) * TIME_ESTIMATES["lag_formula"]
    return int(total)


def format_time_saved(minutes: int) -> str:
    if minutes < 60:
        return f"~{minutes} minutes"
    hours = minutes // 60
    rem = minutes % 60
    if rem == 0:
        return f"~{hours} hour{'s' if hours != 1 else ''}"
    return f"~{hours}h {rem}m"


def build_impact(action: str, stats: Dict[str, Any], scenario: str, trophy: str, **message_kwargs: Any) -> Dict[str, Any]:
    time_saved = calculate_time_saved(stats)
    merged_stats = dict(stats)
    merged_stats["time_saved_minutes"] = time_saved
    return {
        "action": action,
        "stats": merged_stats,
        "gremlin_says": get_gremlin_message(scenario, **message_kwargs),
        "trophy": trophy,
        "time_saved_formatted": format_time_saved(time_saved),
    }


def print_impact_box(impact: Dict[str, Any]) -> None:
    lines: List[str] = []
    lines.append(f"{impact.get('trophy','')} {impact.get('action','').upper()}")
    lines.append("")
    for key, value in impact.get("stats", {}).items():
        if key == "time_saved_minutes":
            continue
        label = key.replace("_", " ").title()
        lines.append(f"{label}: {value}")
    ts = impact.get("stats", {}).get("time_saved_minutes", 0)
    if ts:
        lines.append(f"Time saved: {impact.get('time_saved_formatted','')}")
    lines.append("")
    lines.append(f"\"{impact.get('gremlin_says','')}\"")

    width = max(len(line) for line in lines) + 4
    border = "+" + "-" * (width - 2) + "+"
    print(border, file=sys.stderr)
    print(f"| {'GREMLIN REPORT':<{width-4}} |", file=sys.stderr)
    print(border.replace("-", "="), file=sys.stderr)
    for line in lines:
        print(f"| {line:<{width-4}} |", file=sys.stderr)
    print(border, file=sys.stderr)


def update_stats(command: str, stats: Dict[str, Any]) -> None:
    STATS_FILE.parent.mkdir(parents=True, exist_ok=True)
    if STATS_FILE.exists():
        data = json.loads(STATS_FILE.read_text(encoding="utf-8"))
    else:
        data = {"session_start": datetime.utcnow().isoformat(), "commands": {}, "totals": {}, "achievements": []}

    data["commands"][command] = data["commands"].get(command, 0) + 1
    for key, value in stats.items():
        if isinstance(value, (int, float)):
            data["totals"][key] = data["totals"].get(key, 0) + value
    data["achievements"] = check_achievements(data["totals"])

    STATS_FILE.write_text(json.dumps(data, indent=2), encoding="utf-8")


def check_achievements(totals: Dict[str, Any]) -> List[Dict[str, Any]]:
    unlocked: List[Dict[str, Any]] = []
    for ach_id, ach in ACHIEVEMENTS.items():
        stat_value = totals.get(ach["stat"], 0)
        unlocked.append(
            {
                "id": ach_id,
                "name": ach["name"],
                "emoji": ach["emoji"],
                "desc": ach["desc"],
                "unlocked": stat_value >= ach["threshold"],
                "progress": f"{stat_value}/{ach['threshold']}",
            }
        )
    return unlocked


def get_stats_display() -> str:
    if not STATS_FILE.exists():
        return "No stats yet. The gremlin is waiting for work."
    data = json.loads(STATS_FILE.read_text(encoding="utf-8"))
    totals = data.get("totals", {})
    commands = data.get("commands", {})
    achievements = data.get("achievements", [])
    time_saved = calculate_time_saved(totals)

    lines = [
        "+---------------------------------------------------------+",
        "| GREMLIN STATS                                           |",
        f"| Session: {data.get('session_start','unknown')[:10]:<47} |",
        "+---------------------------------------------------------+",
        f"| Commands run:           {sum(commands.values()):<32} |",
        f"| Formulas inspected:     {int(totals.get('formulas_inspected',0)):<32} |",
        f"| Issues found:           {int(totals.get('issues_found',0)):<32} |",
        f"| Issues auto-fixed:      {int(totals.get('issues_fixed',0)):<32} |",
        f"| Backups created:        {int(totals.get('backups_created',0)):<32} |",
        f"| Cross-sheet refs saved: {int(totals.get('cross_sheet_refs_preserved',0)):<32} |",
        f"| Estimated time saved:   {format_time_saved(time_saved):<32} |",
        "+---------------------------------------------------------+",
        "| ACHIEVEMENTS                                            |",
    ]
    for ach in achievements:
        status = "[x]" if ach.get("unlocked") else "[ ]"
        lines.append(f"| {status} {ach['name']:<20} - {ach['desc']:<24} |")
    lines.extend(
        [
            "+---------------------------------------------------------+",
            '| "You used to have problems. Now you have a gremlin."    |',
            "+---------------------------------------------------------+",
        ]
    )
    return "\n".join(lines)
