#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Schema and procedure quality audits.

Split from metacognitive_audit.py for Law 7 compliance.
"""
from pathlib import Path

from pulse.core.brain_utils import (
    HIPPOCAMPUS_DIR, load_json_dict,
)

SCHEMAS_FILE = HIPPOCAMPUS_DIR / "Patterns" / "schemas.json"
PROCEDURAL_LOG = HIPPOCAMPUS_DIR / "Evidence" / "Metrics" / "procedural_log.json"


def audit_low_evidence_schemas(verbose=False):
    """Find schemas with low confidence or insufficient evidence."""
    data = load_json_dict(SCHEMAS_FILE)
    schemas = data.get("schemas", [])
    weak = []

    for s in schemas:
        issues = []
        if s.get("confidence", 0) < 0.5:
            issues.append(f"low confidence ({s.get('confidence', 0):.2f})")
        if s.get("evidence_count", 0) < 2:
            issues.append(f"low evidence ({s.get('evidence_count', 0)})")

        if issues:
            weak.append({
                "schema_id": s.get("schema_id", "?"),
                "name": s.get("name", "?")[:60],
                "confidence": s.get("confidence", 0),
                "evidence_count": s.get("evidence_count", 0),
                "issues": issues,
            })

    if verbose:
        print(f"[AUDIT] Weak schemas: {len(weak)} of {len(schemas)}")

    return weak


def audit_failing_procedures(verbose=False):
    """Find procedures with <50% success rate."""
    data = load_json_dict(PROCEDURAL_LOG)
    procedures = data.get("procedures", [])
    failing = []

    for p in procedures:
        executions = p.get("executions", 0)
        if executions < 2:
            continue

        success_rate = p.get("success_rate", 0)
        if success_rate < 0.5:
            failing.append({
                "procedure_id": p.get("procedure_id", "?"),
                "name": p.get("name", "?"),
                "success_rate": success_rate,
                "executions": executions,
                "domain": p.get("domain", "general"),
            })

    if verbose:
        print(f"[AUDIT] Failing procedures: {len(failing)} of {len(procedures)}")

    return failing
