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

from __future__ import annotations

from typing import List, Optional

from packages.artifacts.design import DesignArtifact, enforce_allowlist
from packages.artifacts.requirements import RequirementsArtifact
from packages.integrations.llm import LLMClient, get_llm_client
from packages.knowledge.retrievers import KnowledgeHit, KnowledgeService


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

    async def design(self, requirements: RequirementsArtifact) -> DesignArtifact:
        query = f"{requirements.summary} {' '.join(requirements.acceptance_criteria)}"
        hits = await self.knowledge.gather(query, limit=5)
        prompt = build_architect_prompt(requirements, hits)
        artifact = await self.llm.design_solution(prompt)
        artifact.jira_key = requirements.jira_key
        if not artifact.summary:
            artifact.summary = requirements.summary
        return enforce_allowlist(artifact)


def build_architect_prompt(requirements: RequirementsArtifact, hits: List[KnowledgeHit]) -> 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)}

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.
"""
