"""Coding standards file, automatic checks, and prompt wiring."""

from __future__ import annotations

import json
import os
import time
from pathlib import Path

import pytest

from packages.agents.code_reviewer import _static_violations_to_findings, build_review_prompt
from packages.agents.salesforce_developer import build_fix_prompt
from packages.artifacts.design import DesignArtifact, MetadataPlanItem
from packages.artifacts.implementation import ImplementationArtifact
from packages.artifacts.requirements import RequirementsArtifact
from packages.artifacts.review import ReviewArtifact, ReviewFinding
from packages.config import Settings
from packages.db.models import WorkflowState
from packages.integrations.standards_check import check_standards, merge_standards_results
from packages.integrations.static_analysis import StaticAnalysisResult
from packages.knowledge.coding_standards import (
    PROJECT_ROOT,
    load_coding_standards,
    parse_coding_standards,
)
from packages.orchestrator.graph import Orchestrator, create_run
from tests.conftest import load_story

CLS = "force-app/main/default/classes/"
FIELDS = "force-app/main/default/objects/Account/fields/"
VRS = "force-app/main/default/objects/Account/validationRules/"
NS = 'xmlns="http://soap.sforce.com/2006/04/metadata"'


@pytest.fixture()
def standards():
    return load_coding_standards(Settings(coding_standards_path="docs/CODING_STANDARDS.md"))


def _rules(violations):
    return sorted({v.rule for v in violations})


def test_repo_standards_file_parses(standards):
    assert standards.path == str(PROJECT_ROOT / "docs/CODING_STANDARDS.md")
    assert standards.has("APEX-01")
    assert standards.rules["APEX-01"].level == "MUST"
    assert standards.rules["APEX-01"].auto is True
    assert standards.rules["APEX-01"].severity == "high"
    assert standards.rules["APEX-01"].section == "Apex"
    should = [r for r in standards.rules.values() if r.level == "SHOULD"]
    assert should and all(r.severity == "medium" for r in should)


def test_parse_rule_format():
    text = """# Standards
## Apex
- **APEX-01** MUST [auto]: Declare sharing.
- **APEX-09** SHOULD: Prefer small methods.
Not a rule line.
## Flows
* **FLOW-01** MUST: Name flows well.
"""
    s = parse_coding_standards(text)
    assert list(s.rules) == ["APEX-01", "APEX-09", "FLOW-01"]
    assert s.rules["APEX-09"].auto is False
    assert s.rules["FLOW-01"].section == "Flows"
    block = s.prompt_block(sections=["flows"])
    assert "FLOW-01" in block and "APEX-01" not in block
    assert "APEX-09" in s.prompt_block(rule_ids=["APEX-09"])


def test_missing_file_gives_empty_standards(tmp_path):
    s = load_coding_standards(Settings(coding_standards_path=str(tmp_path / "nope.md")))
    assert s.rules == {}
    assert "no coding standards" in s.prompt_block()
    assert check_standards({CLS + "A.cls": "public class A {}"}, s) == []


def test_edits_picked_up_without_restart(tmp_path):
    path = tmp_path / "STANDARDS.md"
    path.write_text("## Apex\n- **APEX-01** MUST [auto]: Declare sharing.\n")
    settings = Settings(coding_standards_path=str(path))
    assert load_coding_standards(settings).has("APEX-01")
    path.write_text("## Apex\n- **APEX-06** SHOULD [auto]: No debug.\n")
    later = time.time() + 5
    os.utime(path, (later, later))
    reloaded = load_coding_standards(settings)
    assert not reloaded.has("APEX-01") and reloaded.has("APEX-06")


def test_apex_sharing_rule(standards):
    bad = check_standards({CLS + "A.cls": "public class A {\n}\n"}, standards)
    assert _rules(bad) == ["APEX-01"]
    assert bad[0].severity == "high"
    assert bad[0].message.startswith("APEX-01:")

    unjustified = "public without sharing class A {\n}\n"
    assert _rules(check_standards({CLS + "A.cls": unjustified}, standards)) == ["APEX-01"]

    justified = "// Runs as system to read restricted config\npublic without sharing class A {\n}\n"
    good = "public with sharing class A {\n}\n"
    inherited = "public inherited sharing class A {\n}\n"
    for src in (justified, good, inherited):
        assert check_standards({CLS + "A.cls": src}, standards) == []


def test_apex_test_class_rules(standards):
    no_assert = "@isTest\nprivate class ATest {\n  @isTest static void t() { A.run(); }\n}\n"
    found = check_standards({CLS + "ATest.cls": no_assert}, standards)
    assert _rules(found) == ["APEX-02"]

    missing_annotation = "public with sharing class ATest {\n  static void t() { Assert.isTrue(true); }\n}\n"
    assert _rules(check_standards({CLS + "ATest.cls": missing_annotation}, standards)) == ["APEX-02"]

    good = "@isTest\nprivate class ATest {\n  @isTest static void t() { A.run(); Assert.isTrue(true); }\n}\n"
    assert check_standards({CLS + "ATest.cls": good}, standards) == []


def test_hardcoded_ids_and_debug(standards):
    src = (
        "public with sharing class A {\n"
        "  public static void run() {\n"
        "    Id owner = '005000000000001AAA';\n"
        "    System.debug('x');\n"
        "  }\n"
        "}\n"
    )
    found = check_standards({CLS + "A.cls": src}, standards)
    assert _rules(found) == ["APEX-05", "APEX-06"]
    by_rule = {v.rule: v for v in found}
    assert by_rule["APEX-05"].line == 3
    assert by_rule["APEX-06"].severity == standards.rules["APEX-06"].severity


def test_trigger_logic_rule(standards):
    thin = "trigger AccountTrigger on Account (before insert) {\n  AccountHandler.run(Trigger.new);\n}\n"
    fat = "trigger AccountTrigger on Account (before insert) {\n" + "  Integer i = 0;\n" * 7 + "}\n"
    path = "force-app/main/default/triggers/AccountTrigger.trigger"
    assert check_standards({path: thin}, standards) == []
    assert _rules(check_standards({path: fat}, standards)) == ["TRIG-01"]


def test_lwc_console_log(standards):
    path = "force-app/main/default/lwc/tierBadge/tierBadge.js"
    bad = "export default class TierBadge {\n  connectedCallback() { console.log('hi'); }\n}\n"
    good = "export default class TierBadge {\n  // console.log('commented out')\n}\n"
    assert _rules(check_standards({path: bad}, standards)) == ["LWC-02"]
    assert check_standards({path: good}, standards) == []


def test_field_name_and_description(standards):
    good = f'<CustomField {NS}><fullName>Customer_Tier__c</fullName><description>Tier</description></CustomField>'
    no_desc = f'<CustomField {NS}><fullName>Customer_Tier__c</fullName></CustomField>'
    assert check_standards({FIELDS + "Customer_Tier__c.field-meta.xml": good}, standards) == []
    assert _rules(check_standards({FIELDS + "Customer_Tier__c.field-meta.xml": no_desc}, standards)) == ["FIELD-02"]
    assert _rules(check_standards({FIELDS + "customer_tier__c.field-meta.xml": good}, standards)) == ["FIELD-01"]


def test_validation_rule_error_message(standards):
    good = f"<ValidationRule {NS}><fullName>Tier_Required</fullName><errorMessage>Set a tier.</errorMessage></ValidationRule>"
    bad = f"<ValidationRule {NS}><fullName>Tier_Required</fullName></ValidationRule>"
    assert check_standards({VRS + "Tier_Required.validationRule-meta.xml": good}, standards) == []
    assert _rules(check_standards({VRS + "Tier_Required.validationRule-meta.xml": bad}, standards)) == ["VR-02"]


def test_non_force_app_paths_skipped(standards):
    assert check_standards({"scripts/A.cls": "public class A {}"}, standards) == []


def test_removing_rule_disables_its_check(standards):
    text = standards.text.replace("**APEX-01**", "**REMOVED**")
    reduced = parse_coding_standards(text)
    assert not reduced.has("APEX-01")
    assert check_standards({CLS + "A.cls": "public class A {\n}\n"}, reduced) == []


def test_merge_and_findings_category(standards):
    violations = check_standards({CLS + "A.cls": "public class A {\n}\n"}, standards)
    merged = merge_standards_results(StaticAnalysisResult(success=True, violations=[], message="PMD ok"), violations)
    assert "coding standards" in merged.message
    findings = _static_violations_to_findings(merged)
    assert [(f.category, f.severity) for f in findings] == [("standards", "high")]
    assert findings[0].message.startswith("APEX-01:")


def _design() -> DesignArtifact:
    return DesignArtifact(
        jira_key="SALES-900",
        summary="Tier",
        approach="Apex",
        metadata_plan=[MetadataPlanItem(metadata_type="ApexClass", api_name="TierService", action="create")],
    )


def test_review_and_fix_prompts_include_standards():
    requirements = RequirementsArtifact(
        jira_key="SALES-900", summary="Tier", acceptance_criteria=["Tier set"], is_clear=True, confidence=0.9
    )
    files = {CLS + "TierService.cls": "public class TierService {}"}
    review_prompt = build_review_prompt(
        requirements=requirements,
        design=_design(),
        implementation=ImplementationArtifact(jira_key="SALES-900", summary="impl", commit_message="SALES-900 tier"),
        file_map=files,
        static_analysis=StaticAnalysisResult(success=True, violations=[]),
        cycle=0,
    )
    assert "Team coding standards" in review_prompt
    assert "APEX-01 MUST" in review_prompt
    assert 'category="standards"' in review_prompt

    fix_prompt = build_fix_prompt(
        review=ReviewArtifact(
            jira_key="SALES-900",
            passed=False,
            cycle=0,
            findings=[ReviewFinding(severity="high", category="standards", message="APEX-01: x", fixable=True)],
            summary="fail",
        ),
        design=_design(),
        requirements=requirements,
        file_map=files,
    )
    assert "Team coding standards" in fix_prompt
    assert "APEX-01 MUST" in fix_prompt


@pytest.mark.asyncio
async def test_orchestrator_writes_standards_artifact(db_session, mock_jira, artifacts_tmpdir):
    from packages.agents.code_reviewer import CodeReviewer
    from packages.agents.solution_architect import SolutionArchitect

    class ApexArchitect(SolutionArchitect):
        async def design(self, *args, **kwargs):
            design = await super().design(*args, **kwargs)
            design.metadata_plan.append(
                MetadataPlanItem(metadata_type="ApexClass", api_name="AccountTierService", action="create")
            )
            return design

    seen = []
    reviews = []

    class RecordingReviewer:
        async def review(self, **kwargs):
            seen.append(kwargs["static_analysis"])
            review = await CodeReviewer().review(**kwargs)
            reviews.append(review)
            return review

    issue = load_story("SALES-101")
    mock_jira.seed(issue)
    run = await create_run(db_session, issue.key)
    class PassingQA:
        async def run_qa(self, **kwargs):
            from packages.artifacts.qa_report import QAReportArtifact
            from packages.db.artifacts import ArtifactStore

            artifact = QAReportArtifact(
                jira_key=kwargs["requirements"].jira_key, passed=True, test_matrix=[], summary="QA passed"
            )
            ArtifactStore().write_json(kwargs["run_id"], "qa-report.json", artifact)
            return artifact

    orch = Orchestrator(
        db_session, jira=mock_jira, architect=ApexArchitect(), reviewer=RecordingReviewer(), qa=PassingQA()
    )
    paused = await orch.run(run.id)
    assert paused.state == WorkflowState.DESIGN_REVIEW

    arts = dict(paused.artifacts or {})
    arts["design_decision"] = "approve"
    arts["design_resume_comment"] = "approve"
    paused.artifacts = arts
    await db_session.flush()

    done = await orch.run(run.id, resume=True)
    assert done.state == WorkflowState.PR_CREATED
    standards_path = Path(done.artifacts["standards.json"])
    assert standards_path.exists()
    payload = json.loads(standards_path.read_text())
    assert payload["source"].endswith("CODING_STANDARDS.md")
    assert isinstance(payload["violations"], list)
    assert "APEX-01" in {v.rule for v in seen[0].violations}
    assert any(
        f.category == "standards" and f.message.startswith("APEX-01: class") for f in reviews[0].findings
    )
    assert reviews[-1].passed
    assert not any(v["severity"] == "high" for v in payload["violations"])
