"""
Agent 2: ARCHITECT
==================
Designs the complete file/folder structure and inter-file dependency map.
Senior React Native architect thinking: separation of concerns, scalability.
"""
from __future__ import annotations

from forge.core.session import GenerationSession, AppPlan
from forge.core.api import GroqClient

ARCHITECT_SYSTEM = """You are a Principal React Native Architect. Given an app plan, produce
the complete professional file structure as JSON.

Think like a senior engineer building an app that will be maintained for 3 years by a team.

OUTPUT: Valid JSON ONLY. No markdown.

Schema:
{
  "files": [
    {
      "path": "src/screens/HomeScreen.tsx",
      "type": "screen|component|navigation|context|hook|util|constant|type|service|test|config",
      "purpose": "concise one-line purpose",
      "exports": ["default HomeScreen", "named export if any"],
      "imports": ["what it needs from other project files"],
      "isEntry": false,
      "priority": 1
    }
  ],
  "entryFile": "App.tsx",
  "navigationFile": "src/navigation/AppNavigator.tsx",
  "themeFile": "src/constants/theme.ts",
  "contextFile": "src/context/AppContext.tsx",
  "typesFile": "src/types/index.ts",
  "storageFile": "src/services/storage.ts"
}

MANDATORY FILES (always include):
- App.tsx (entry, registers navigation)
- package.json
- app.json
- babel.config.js
- tsconfig.json
- .gitignore
- .env.example
- src/navigation/AppNavigator.tsx
- src/constants/theme.ts (colors, spacing, typography)
- src/constants/index.ts (app-wide constants)
- src/types/index.ts (all TypeScript interfaces/types)
- src/context/AppContext.tsx (global state with useReducer)
- src/services/storage.ts (AsyncStorage abstraction layer)
- src/utils/helpers.ts (pure utility functions)
- src/hooks/useApp.ts (main app hook consuming context)
- src/components/ui/Button.tsx (reusable button)
- src/components/ui/Card.tsx (reusable card)
- src/components/ui/EmptyState.tsx (empty list state)
- src/components/ui/LoadingSpinner.tsx
- src/components/ui/Header.tsx
- One file per screen

OPTIONAL (include when relevant):
- src/services/api.ts (if external APIs)
- src/hooks/useStorage.ts (if heavy storage)
- src/components/ui/Modal.tsx (if modals used)
- src/components/ui/SearchBar.tsx (if search exists)

RULES:
- Use TypeScript (.tsx / .ts) throughout
- Group: screens/, components/ui/, components/[feature]/, navigation/, context/, hooks/, services/, utils/, constants/, types/
- priority: 1=entry/nav/types, 2=context/services, 3=components, 4=screens, 5=tests
"""


async def run_architect(
    session: GenerationSession,
    groq: GroqClient,
) -> dict:
    plan = session.plan
    model = session.settings.plan_model

    agent = session.start_agent("ARCHITECT", f"Groq → {model}")
    session.log("ARCHITECT", "Designing professional file structure…")

    screens_list = [s["name"] for s in plan.screens]
    models_list = [m["name"] for m in plan.data_models]

    user_msg = f"""Design the complete file structure for:

App: {plan.app_name}
Description: {plan.description}
Screens: {screens_list}
Navigation: {plan.navigation} (tab: {plan.tab_screens}, stack: {plan.stack_screens})
Storage: {plan.storage}
Data Models: {models_list}
Auth: {plan.auth_method}
External APIs: {plan.external_apis}
Features: {plan.features[:6]}

Include TypeScript types for ALL data models: {models_list}
"""

    arch = await groq.complete_json(
        messages=[
            {"role": "system", "content": ARCHITECT_SYSTEM},
            {"role": "user", "content": user_msg},
        ],
        model=model,
        temperature=0.15,
    )

    files = arch.get("files", [])
    # Sort by priority
    files.sort(key=lambda f: f.get("priority", 5))

    session.log("ARCHITECT", f"✓ {len(files)} files planned")

    # Group by directory for cleaner logging
    dirs: dict[str, list[str]] = {}
    for f in files:
        parts = f["path"].split("/")
        d = "/".join(parts[:-1]) or "root"
        dirs.setdefault(d, []).append(parts[-1])

    for d, fnames in sorted(dirs.items()):
        session.log("ARCHITECT", f"  {d}/  → {', '.join(fnames)}")

    session.architecture = arch
    session.finish_agent(agent, files=len(files))

    return arch
