"""Automatic checks for the [auto] rules in docs/CODING_STANDARDS.md."""

from __future__ import annotations

import re
import xml.etree.ElementTree as ET
from pathlib import PurePosixPath
from typing import Callable, Dict, List, Optional

from packages.integrations.governor_limits import _strip_comments_and_strings
from packages.integrations.static_analysis import StaticAnalysisResult, StaticViolation
from packages.knowledge.coding_standards import CodingStandards, load_coding_standards

_NS = "{http://soap.sforce.com/2006/04/metadata}"

_IS_TEST = re.compile(r"@\s*isTest\b", re.IGNORECASE)
_TOP_CLASS = re.compile(
    r"^(?P<prefix>(?:\s*@\w+(?:\([^)]*\))?\s*)*)\s*(?:global|public|private)?\s*(?:virtual\s+|abstract\s+)?"
    r"(?P<sharing>(?:with|without|inherited)\s+sharing\s+)?(?:virtual\s+|abstract\s+)?class\s+(?P<name>\w+)",
    re.IGNORECASE | re.MULTILINE,
)
_ASSERT = re.compile(r"\b(?:System\s*\.\s*assert\w*|Assert\s*\.\s*\w+)\s*\(", re.IGNORECASE)
_DEBUG = re.compile(r"\bSystem\s*\.\s*debug\s*\(", re.IGNORECASE)
_CONSOLE_LOG = re.compile(r"\bconsole\s*\.\s*log\s*\(")
# 15/18-char IDs with common key prefixes (Account 001, Contact 003, Opportunity 006, User 005,
# Profile 00e, RecordType 012, Case 500, Lead 00Q, Group/Queue 00G, custom objects a0x)
_RECORD_ID = re.compile(
    r"(?<![A-Za-z0-9])(?:001|003|005|006|00e|00E|012|500|00Q|00G|a0[0-9A-Za-z])[0-9A-Za-z]{12}(?:[0-9A-Za-z]{3})?(?![A-Za-z0-9])"
)
_FIELD_NAME = re.compile(r"^[A-Z][A-Za-z0-9]*(?:_[A-Z0-9][A-Za-z0-9]*)*__c$")
_TRIGGER_BODY = re.compile(r"\btrigger\s+\w+\s+on\s+\w+\s*\([^)]*\)\s*\{(?P<body>.*)\}", re.IGNORECASE | re.S)
TRIGGER_MAX_CODE_LINES = 5


def _line_of(text: str, index: int) -> int:
    return text.count("\n", 0, index) + 1


def _violation(standards: CodingStandards, rule_id: str, path: str, message: str, line: Optional[int] = None):
    rule = standards.rules[rule_id]
    return StaticViolation(
        rule=rule_id, file=path, line=line, message=f"{rule_id}: {message}", severity=rule.severity
    )


def check_apex_class(path: str, source: str, standards: CodingStandards) -> List[StaticViolation]:
    out: List[StaticViolation] = []
    code = _strip_comments_and_strings(source)
    is_test = bool(_IS_TEST.search(code))
    m = _TOP_CLASS.search(code)

    if standards.has("APEX-01") and m and not is_test:
        sharing = (m.group("sharing") or "").lower()
        line = _line_of(code, m.start("name"))
        if not sharing:
            out.append(_violation(standards, "APEX-01", path, f"class {m.group('name')} has no sharing declaration; use 'with sharing' or 'inherited sharing'", line))
        elif sharing.startswith("without"):
            prev = source.splitlines()[line - 2].strip() if line >= 2 else ""
            if not prev.startswith("//"):
                out.append(_violation(standards, "APEX-01", path, f"class {m.group('name')} uses 'without sharing' without a justification comment on the line above", line))

    if standards.has("APEX-02") and m:
        name = m.group("name")
        if name.lower().endswith("test") and not is_test:
            out.append(_violation(standards, "APEX-02", path, f"test class {name} is missing @isTest", _line_of(code, m.start("name"))))
        if is_test and not _ASSERT.search(code):
            out.append(_violation(standards, "APEX-02", path, f"test class {name} has no assertions (Assert.* or System.assert*)"))

    if standards.has("APEX-05"):
        for idm in _RECORD_ID.finditer(source):
            out.append(_violation(standards, "APEX-05", path, f"hardcoded record ID '{idm.group(0)}'", _line_of(source, idm.start())))

    if standards.has("APEX-06") and not is_test:
        for dm in _DEBUG.finditer(code):
            out.append(_violation(standards, "APEX-06", path, "System.debug left in non-test code", _line_of(code, dm.start())))
    return out


def check_trigger(path: str, source: str, standards: CodingStandards) -> List[StaticViolation]:
    out = check_apex_class(path, source, standards) if standards.has("APEX-05") else []
    out = [v for v in out if v.rule == "APEX-05"]
    if standards.has("TRIG-01"):
        code = _strip_comments_and_strings(source)
        m = _TRIGGER_BODY.search(code)
        if m:
            lines = [ln for ln in m.group("body").splitlines() if ln.strip()]
            if len(lines) > TRIGGER_MAX_CODE_LINES:
                out.append(_violation(standards, "TRIG-01", path, f"trigger has {len(lines)} lines of logic; move it to a handler class", _line_of(code, m.start("body"))))
    return out


def _xml_text(root: ET.Element, tag: str) -> str:
    el = root.find(f"{_NS}{tag}")
    if el is None:
        el = root.find(tag)
    return (el.text or "").strip() if el is not None else ""


def _parse_xml(text: str) -> Optional[ET.Element]:
    try:
        return ET.fromstring(text)
    except ET.ParseError:
        return None


def check_field(path: str, xml_text: str, standards: CodingStandards) -> List[StaticViolation]:
    out: List[StaticViolation] = []
    api_name = PurePosixPath(path).name.replace(".field-meta.xml", "")
    if standards.has("FIELD-01") and api_name.endswith("__c") and not _FIELD_NAME.match(api_name):
        out.append(_violation(standards, "FIELD-01", path, f"field API name '{api_name}' should be PascalCase words joined by underscores (e.g. Customer_Tier__c)"))
    root = _parse_xml(xml_text)
    if standards.has("FIELD-02") and root is not None and not _xml_text(root, "description"):
        out.append(_violation(standards, "FIELD-02", path, f"field {api_name} has no <description>"))
    return out


def check_validation_rule(path: str, xml_text: str, standards: CodingStandards) -> List[StaticViolation]:
    root = _parse_xml(xml_text)
    if standards.has("VR-02") and root is not None and not _xml_text(root, "errorMessage"):
        name = PurePosixPath(path).name.replace(".validationRule-meta.xml", "")
        return [_violation(standards, "VR-02", path, f"validation rule {name} has no <errorMessage>")]
    return []


def check_flow(path: str, xml_text: str, standards: CodingStandards) -> List[StaticViolation]:
    out: List[StaticViolation] = []
    root = _parse_xml(xml_text)
    name = PurePosixPath(path).name.replace(".flow-meta.xml", "")
    if standards.has("FLOW-02") and root is not None and not _xml_text(root, "description"):
        out.append(_violation(standards, "FLOW-02", path, f"Flow {name} has no <description>"))
    if standards.has("FLOW-05"):
        for idm in _RECORD_ID.finditer(xml_text):
            out.append(_violation(standards, "FLOW-05", path, f"hardcoded record ID '{idm.group(0)}'", _line_of(xml_text, idm.start())))
    return out


def check_lwc_js(path: str, source: str, standards: CodingStandards) -> List[StaticViolation]:
    if not standards.has("LWC-02"):
        return []
    code = _strip_comments_and_strings(source)
    return [
        _violation(standards, "LWC-02", path, "console.log left in component code", _line_of(code, m.start()))
        for m in _CONSOLE_LOG.finditer(code)
    ]


_CHECKS: List[tuple[Callable[[str], bool], Callable[[str, str, CodingStandards], List[StaticViolation]]]] = [
    (lambda p: p.endswith(".cls"), check_apex_class),
    (lambda p: p.endswith(".trigger"), check_trigger),
    (lambda p: p.endswith(".field-meta.xml"), check_field),
    (lambda p: p.endswith(".validationRule-meta.xml"), check_validation_rule),
    (lambda p: p.endswith(".flow-meta.xml"), check_flow),
    (lambda p: "/lwc/" in p and p.endswith(".js"), check_lwc_js),
]


def check_standards(
    file_map: Dict[str, str], standards: Optional[CodingStandards] = None
) -> List[StaticViolation]:
    """Run the automatic checks whose rule IDs exist in the standards file."""
    standards = standards if standards is not None else load_coding_standards()
    if not standards.rules:
        return []
    violations: List[StaticViolation] = []
    for path, content in sorted(file_map.items()):
        if not path.startswith("force-app/"):
            continue
        for matches, check in _CHECKS:
            if matches(path):
                violations.extend(check(path, content, standards))
    return violations


def merge_standards_results(
    static_result: StaticAnalysisResult, violations: List[StaticViolation]
) -> StaticAnalysisResult:
    if not violations:
        return static_result
    return StaticAnalysisResult(
        success=static_result.success,
        violations=list(static_result.violations) + violations,
        message=f"{static_result.message}; coding standards checks found {len(violations)} violation(s)",
    )
