"""
Agent 1: PLANNER
================
Converts natural language into a rigorous, structured app specification.
- Multi-turn clarification (asks questions before committing)
- Produces JSON app plan with screens, models, features, user stories
- Senior PM + UX architect thinking
"""
from __future__ import annotations
import json
from forge.core.session import GenerationSession, AppPlan
from forge.core.api import GroqClient

PLANNER_SYSTEM = """You are a Principal Product Manager and UX Architect at a top-tier mobile app studio.
Your job: transform user app ideas into rigorous, professional app specifications.

Think like a senior PM who has shipped 50 production apps. Ask yourself:
- What does the user REALLY want vs what they said?
- What are the 3 must-have screens for day 1?
- What data persists? What's ephemeral?
- What are the obvious edge cases (empty state, error state, loading)?
- What would make this app actually used vs deleted in a week?

OUTPUT: Valid JSON ONLY. No markdown. No explanation. No preamble.

Schema (all fields required):
{
  "appName": "Title Case Name (2-3 words max)",
  "packageName": "com.yourname.appslug",
  "tagline": "One-line value proposition",
  "description": "2-3 sentences. What it does, who it's for, why it's better.",

  "primaryColor": "#hexcode (brand primary)",
  "accentColor": "#hexcode (CTA, highlights)",
  "backgroundColor": "#hexcode (main background)",
  "surfaceColor": "#hexcode (cards, sheets)",
  "textColor": "#hexcode (primary text)",

  "screens": [
    {
      "name": "ExactScreenName",
      "fileName": "ExactScreenName.tsx",
      "purpose": "Single sentence purpose",
      "primaryAction": "The main thing user does here",
      "components": ["ComponentA", "ComponentB"],
      "dataFlow": "reads X from storage, writes Y to context",
      "emptyState": "Message when no data",
      "hasSearch": false,
      "hasFAB": false,
      "hasBottomSheet": false
    }
  ],

  "dataModels": [
    {
      "name": "ModelName",
      "description": "What this model represents",
      "fields": [
        {"name": "id", "type": "string", "generated": true, "required": true},
        {"name": "createdAt", "type": "Date", "generated": true, "required": true},
        {"name": "updatedAt", "type": "Date", "generated": true, "required": true}
      ],
      "relationships": []
    }
  ],

  "features": [
    "Exact feature description with technical detail"
  ],
  "userStories": [
    "As a user, I want to... so that..."
  ],

  "navigation": "tab",
  "tabScreens": ["HomeScreen", "StatsScreen", "SettingsScreen"],
  "stackScreens": ["DetailScreen", "CreateScreen", "EditScreen"],
  "drawerScreens": [],

  "storage": "asyncstorage",
  "storageKey": "app_data_v1",
  "authRequired": false,
  "authMethod": "none",

  "externalAPIs": [],
  "dependencies": ["@react-native-community/datetimepicker@7.7.0"],
  "devDependencies": ["@testing-library/react-native@12.4.3"],

  "targetPlatforms": ["ios", "android"],
  "assumptions": [
    "Offline-first: all data stored locally in AsyncStorage"
  ],
  "clarifyingQuestions": []
}

SCREEN COUNT RULES:
- minimal: exactly 4 screens
- standard: exactly 7 screens
- full: exactly 12 screens
- enterprise: exactly 18 screens

QUALITY RULES:
- Every screen has a distinct, non-overlapping purpose
- Data models cover ALL data the screens need
- Colors form a real professional palette (not random)
- Dependencies are real valid npm packages with versions
- No "placeholder", no "TODO", no "example" content
- Think: would this pass a Google design review?
"""


async def run_planner(
    session: GenerationSession,
    groq: GroqClient,
) -> AppPlan:
    complexity = session.settings.complexity
    model = session.settings.plan_model

    agent = session.start_agent("PLANNER", f"Groq → {model}")
    session.log("PLANNER", f'Analyzing prompt: "{session.prompt}"')
    session.log("PLANNER", f"Complexity: {complexity} | Framework: {session.settings.framework}")

    screen_count = {"minimal": 4, "standard": 7, "full": 12, "enterprise": 18}[complexity]

    # Include any clarification answers in context
    clarification_ctx = ""
    if session.clarification_answers:
        clarification_ctx = "\n\nUser clarifications:\n" + "\n".join(
            f"Q: {q}\nA: {a}" for q, a in session.clarification_answers.items()
        )

    user_msg = (
        f"App idea: {session.prompt}{clarification_ctx}\n\n"
        f"Generate exactly {screen_count} screens for '{complexity}' complexity.\n"
        f"Framework: React Native + Expo (TypeScript).\n"
        f"Make every decision deliberate. No filler screens."
    )

    plan_dict = await groq.complete_json(
        messages=[
            {"role": "system", "content": PLANNER_SYSTEM},
            {"role": "user", "content": user_msg},
        ],
        model=model,
        temperature=0.25,
    )

    plan = AppPlan.from_dict(plan_dict)

    # Log plan details
    session.log("PLANNER", f"✓ App: {plan.app_name} — {plan.tagline}")
    session.log("PLANNER", f"  Screens ({len(plan.screens)}): {', '.join(s['name'] for s in plan.screens)}")
    session.log("PLANNER", f"  Navigation: {plan.navigation} | Storage: {plan.storage}")
    session.log("PLANNER", f"  Auth: {plan.auth_method} | Data models: {len(plan.data_models)}")
    session.log("PLANNER", f"  Features: {len(plan.features)} | User stories: {len(plan.user_stories)}")

    if plan.clarifying_questions:
        session.log("PLANNER", f"  Questions: {plan.clarifying_questions}", "warning")
        session.needs_clarification = True

    if plan.assumptions:
        for a in plan.assumptions:
            session.log("PLANNER", f"  Assuming: {a}")

    session.plan = plan
    session.finish_agent(agent, screens=len(plan.screens), models=len(plan.data_models))

    return plan
