"""Claude analysis pass over transactions pulled from Lunch Money.

Usage:
  python analyze.py weekly       # last 7 days
  python analyze.py monthly      # last 30 days
  python analyze.py subscriptions # 90-day window + recurring data
"""
import argparse
import datetime as dt
import json
import os
from pathlib import Path

import anthropic

import db

ROOT = Path(__file__).parent
ANALYSES_DIR = ROOT / "analyses"
ANALYSES_DIR.mkdir(parents=True, exist_ok=True)

CLAUDE_MODEL = "claude-sonnet-4-6"
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

SYSTEM_PROMPT = """You are Cameron's personal financial analyst. He's a 27-year-old USC PhD student / TRI intern, on a stipend + intern salary, living frugally with family-house base, trying to build personal-finance discipline + identify wasteful spending.

For every analysis, output:

## Summary
2-3 sentences: net flow, top categories, any standout.

## Top spending categories
Markdown table with category, total, % of spending, notable payees.

## Recurring charges
Markdown table: payee, cadence, typical amount, last seen. The data already includes Lunch Money's recurring matches — trust them. Flag any that look forgotten/cancelable.

## Anomalies
Single transactions >2x category average, or unexpected payees.

## Savings opportunities
- Idle cash to move to high-yield savings (mention 4-5% APY savings as context, not advice)
- Subscriptions to consider cancelling (be specific — name them)
- Category overspends (compare to a frugal grad-student baseline)

## Recommendations (max 3)
Specific, actionable. Not generic "spend less."

Use raw transaction data. Be direct. Don't moralize."""


def analyze(period: str):
    days = {"weekly": 7, "monthly": 30, "subscriptions": 90}[period]
    txns = db.list_recent_transactions(days)
    if not txns:
        print("No transactions found. Run pull_transactions.py first.")
        return

    end = dt.date.today()
    start = end - dt.timedelta(days=days)

    compact = [
        {
            "date": t["date"],
            "payee": t["payee"],
            "amount": t["amount"],
            "category": t.get("category_name"),
            "recurring": bool(t.get("recurring_id")),
            "pending": bool(t["is_pending"]),
        }
        for t in txns
    ]

    recurring = db.list_recurring()
    recurring_compact = [
        {
            "payee": r["payee"],
            "cadence": r.get("cadence"),
            "amount": r.get("typical_amount"),
            "last_seen": r.get("end_date") or r.get("start_date"),
        }
        for r in recurring
    ]

    user_msg = f"""Analyze these transactions from {start} to {end} ({len(compact)} transactions).
Period: {period}

Transactions (JSON):
{json.dumps(compact, indent=2)}

Lunch Money's detected recurring expenses:
{json.dumps(recurring_compact, indent=2)}

Generate the analysis per the format in your system prompt."""

    resp = client.messages.create(
        model=CLAUDE_MODEL,
        max_tokens=4096,
        system=SYSTEM_PROMPT,
        messages=[{"role": "user", "content": user_msg}],
    )
    md = resp.content[0].text

    out_path = ANALYSES_DIR / f"{period}_{end.isoformat()}.md"
    out_path.write_text(md)
    out_path.chmod(0o600)

    db.save_analysis(
        kind=period,
        period_start=start.isoformat(),
        period_end=end.isoformat(),
        summary_md=md,
        structured_json={"transaction_count": len(compact), "recurring_count": len(recurring)},
    )
    print(f"Saved analysis to {out_path}")
    print("\n" + md)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("period", choices=["weekly", "monthly", "subscriptions"])
    args = ap.parse_args()
    db.init_db()
    analyze(args.period)


if __name__ == "__main__":
    main()
