"""Solution Architect skill — technical design + metadata plan from requirements."""

from __future__ import annotations

from typing import Dict, List, Optional, Tuple
from uuid import UUID

import structlog

from packages.artifacts.design import DesignArtifact, enforce_allowlist
from packages.artifacts.requirements import RequirementsArtifact
from packages.db.artifacts import ArtifactStore
from packages.integrations.github_search import CodeEvidence
from packages.integrations.llm import LLMClient, get_llm_client
from packages.integrations.org_schema import (
    DataModel,
    OrgSchemaProvider,
    detect_objects,
    get_org_schema_provider,
)
from packages.knowledge.coding_standards import load_coding_standards
from packages.knowledge.retrievers import KnowledgeHit, KnowledgeService, classify_metadata_path

logger = structlog.get_logger(__name__)

STANDARDS_DESIGN_SECTIONS = ("Triggers", "Flows", "Custom fields", "Validation rules", "Permission sets")
STANDARDS_DESIGN_RULES = ("APEX-07", "LWC-01")


class SolutionArchitect:
    def __init__(
        self,
        llm: Optional[LLMClient] = None,
        knowledge: Optional[KnowledgeService] = None,
        schema: Optional[OrgSchemaProvider] = None,
        artifacts: Optional[ArtifactStore] = None,
    ) -> None:
        self.llm = llm or get_llm_client()
        self.knowledge = knowledge or KnowledgeService()
        self.schema = schema or get_org_schema_provider()
        self.artifacts = artifacts

    async def design(
        self,
        requirements: RequirementsArtifact,
        run_id: Optional[UUID] = None,
        existing_code: Optional[List[CodeEvidence]] = None,
    ) -> DesignArtifact:
        query = f"{requirements.summary} {' '.join(requirements.acceptance_criteria)}"
        hits = await self.knowledge.gather(query, limit=5)
        data_model = await self.load_data_model(requirements)
        prompt = build_architect_prompt(requirements, hits, data_model, existing_code)
        artifact = await self.llm.design_solution(prompt)
        artifact.jira_key = requirements.jira_key
        if not artifact.summary:
            artifact.summary = requirements.summary
        artifact = enforce_allowlist(artifact)
        apply_data_model_checks(artifact, data_model)
        apply_existing_code_checks(artifact, existing_code or [])
        if run_id is not None:
            store = self.artifacts or ArtifactStore()
            store.write_json(run_id, "data-model.json", data_model)
        return artifact

    async def load_data_model(self, requirements: RequirementsArtifact) -> DataModel:
        text = "\n".join(
            [requirements.summary, *requirements.acceptance_criteria, requirements.notes or ""]
        )
        objects = detect_objects(text)
        if not objects:
            return DataModel(source="none", warnings=["No Salesforce objects detected in requirements"])
        try:
            return await self.schema.describe(objects)
        except Exception as exc:  # noqa: BLE001
            logger.warning("data_model_describe_failed", objects=objects, error=str(exc))
            return DataModel(source="error", warnings=[f"Data model lookup failed: {exc}"])


def apply_data_model_checks(design: DesignArtifact, data_model: DataModel) -> None:
    """Flag plan items that conflict with the discovered data model."""
    risks = design.risks_or_escalations
    for item in design.metadata_plan:
        obj = data_model.get(item.object)
        if item.object and obj is None:
            continue
        if obj is not None and not obj.exists:
            msg = f"Object {obj.name} not found in org/repo — {item.api_name} targets a missing object"
            if msg not in risks:
                risks.append(msg)
            continue
        if item.metadata_type == "CustomField" and obj is not None:
            exists = item.api_name.lower() in obj.field_names()
            if exists and item.action == "create":
                item.action = "update"
                msg = f"{obj.name}.{item.api_name} already exists — plan changed from create to update"
                if msg not in risks:
                    risks.append(msg)
        if item.metadata_type == "ValidationRule" and obj is not None:
            exists = item.api_name.lower() in {v.lower() for v in obj.validation_rules}
            if exists and item.action == "create":
                item.action = "update"
                msg = f"Validation rule {obj.name}.{item.api_name} already exists — plan changed to update"
                if msg not in risks:
                    risks.append(msg)


def _existing_metadata_index(existing: List[CodeEvidence]) -> Dict[Tuple[str, str], CodeEvidence]:
    """(metadata_type, lower name) -> evidence; default-branch files win over open PR files."""
    index: Dict[Tuple[str, str], CodeEvidence] = {}
    for ev in existing:
        if ev.kind not in ("code", "pr_file"):
            continue
        classified = classify_metadata_path(ev.title)
        if not classified:
            continue
        key = (classified[0], classified[1].lower())
        current = index.get(key)
        if current is None or current.state == "open":
            index[key] = ev
    return index


def apply_existing_code_checks(design: DesignArtifact, existing: List[CodeEvidence]) -> None:
    """Flip create->update for metadata already in GitHub; flag open PRs/branches."""
    if not existing:
        return
    risks = design.risks_or_escalations

    def add(msg: str) -> None:
        if msg not in risks:
            risks.append(msg)

    index = _existing_metadata_index(existing)
    for item in design.metadata_plan:
        name = item.api_name
        if item.metadata_type in ("CustomField", "ValidationRule") and item.object and "." not in name:
            name = f"{item.object}.{name}"
        ev = index.get((item.metadata_type, name.lower()))
        if ev is None:
            continue
        where = ev.repo or "GitHub"
        if ev.state == "open":
            add(
                f"{item.metadata_type} {name} is also changed on open branch {ev.ref} in {where} "
                "— coordinate to avoid merge conflicts"
            )
        elif item.action == "create":
            item.action = "update"
            add(f"{item.metadata_type} {name} already exists in {where} ({ev.title}) — plan changed from create to update")

    for ev in existing:
        if ev.kind in ("pr", "branch") and ev.state == "open":
            label = "PR" if ev.kind == "pr" else "branch"
            add(f"Open {label} for {design.jira_key} already exists: {ev.url or ev.title}")


def _existing_code_block(existing: Optional[List[CodeEvidence]]) -> str:
    if not existing:
        return "(none found)"
    lines = []
    for ev in existing:
        snippet = f" — {ev.snippet[:300]}" if ev.snippet else ""
        lines.append(f"- {ev.label()} ({ev.url or 'no url'}){snippet}")
    return "\n".join(lines)


def build_architect_prompt(
    requirements: RequirementsArtifact,
    hits: List[KnowledgeHit],
    data_model: Optional[DataModel] = None,
    existing_code: Optional[List[CodeEvidence]] = None,
) -> str:
    ac = "\n".join(f"- {a}" for a in requirements.acceptance_criteria) or "(none)"
    conf = [h for h in hits if h.source == "confluence"]
    repo = [h for h in hits if h.source == "git"]

    def fmt(hs: List[KnowledgeHit]) -> str:
        if not hs:
            return "(none)"
        return "\n".join(f"- {h.title}: {h.snippet}" for h in hs)

    return f"""You are the Solution Architect for Agent Nova (Salesforce development automation).
Produce a technical design and metadata plan for allowlisted Salesforce metadata only.
Escalate anything outside the v1 allowlist.

The design is published to Confluence as a Technical Design document with these sections:
1. Overview  2. Scope  3. Data Model  4. Picklist Configuration  5. Page Layout Configuration
6. Validation Rule  7. Processing Behavior  8. Security and Access  9. Deployment Components
10. Testing Strategy  11. Acceptance Criteria Traceability  12. Implementation Summary.

Use a concise feature name as summary (example: "Account Segment Classification"), not a sentence.

Jira key: {requirements.jira_key}
Summary: {requirements.summary}
Confidence from analyst: {requirements.confidence}

Acceptance criteria:
{ac}

Out of scope from analyst:
{chr(10).join('- ' + x for x in requirements.out_of_scope_items) if requirements.out_of_scope_items else '(none)'}

Notes: {requirements.notes or '(none)'}

Confluence hits:
{fmt(conf)}

Repository hits:
{fmt(repo)}

Org data model:
{data_model.prompt_block() if data_model else '(not loaded)'}

Existing code in GitHub (kind/state, repo@branch or PR, file, snippet):
{_existing_code_block(existing_code)}

Reuse existing fields and automation from the data model and repository hits. Use action=update
for metadata that already exists; never create a duplicate field. List existing Apex/Flow/triggers
on the same object under dependencies when they may interact with the change.
For existing code in GitHub: plan action=update for those files, never recreate a file that already
exists, and list open pull requests or branches for this ticket under dependencies or risks.

Team naming and metadata standards (api_name values and notes must follow these):
{load_coding_standards().prompt_block(max_chars=3000, sections=STANDARDS_DESIGN_SECTIONS, rule_ids=STANDARDS_DESIGN_RULES)}

v1 allowlist metadata types: CustomField, ValidationRule, Flow (record-triggered), ApexClass, ApexTrigger, LightningComponentBundle, PermissionSet.
Out of scope: profiles, sharing/OWD redesign, connected apps, destructive deletes, production deploy.

Return a metadata_plan with metadata_type, api_name, action (create|update), object (if applicable), and notes.
For CustomField notes include: data type, field label, picklist values, default value, required-at-definition.
For ValidationRule notes include: purpose, formula (Salesforce formula syntax), error message, error location.
"""
