"""Product-scope orchestrator (step 3) — gate, then reuse discover_scope.

THE rule: the Scope Engine decides only once the Navigator has released the
minimum facts. If P0 facts are missing, return the missing facts/questions and do
NOT run discover_scope. Otherwise project the canonical into the reasoning profile
and run the EXISTING `discover_scope` exactly once.

No new scope rules, no new regulations, no environmental-law evaluation (those
domains are surfaced only as unsupported_domains / future_corpus_needed).
"""

from __future__ import annotations

from typing import List, Tuple

from compliance.navigator.engine import navigate
from compliance.profile.canonical import CanonicalProductRegulatoryProfile
from compliance.profile.to_reasoning import to_reasoning_profile
from compliance.reasoning.scope_engine import discover_scope

from .schemas import (
    ProductScopeResponse,
    RegulatoryScopeResult,
    ScopeStatus,
    UnsupportedDomain,
)

# environmental trigger field -> (domain, note). Transparency only — not a verdict.
_ENV_DOMAINS: List[Tuple[str, str, str]] = [
    ("discharges_to_wastewater", "environment_water", "Abwasser-/Gewässerrecht (z. B. AbwV, WRRL) — noch nicht im Korpus."),
    ("has_cooling_or_spraying_water", "environment_water", "Wasserbezogene Anforderungen — noch nicht im Korpus."),
    ("emits_to_air", "environment_air", "Immissionsschutz-/Luftreinhalterecht (z. B. BImSchG, IED) — noch nicht im Korpus."),
    ("uses_solvents", "environment_air", "Lösemittel-/VOC-Recht (z. B. 31. BImSchV) — noch nicht im Korpus."),
    ("uses_cleaning_chemicals", "chemicals", "Chemikalienrecht (REACH/CLP/Detergenzien/Biozide) — noch nicht im Korpus."),
    ("supplies_chemicals", "chemicals", "Chemikalienrecht (REACH/CLP) — noch nicht im Korpus."),
    ("contains_restricted_substances", "chemicals", "Stoffbeschränkungen (REACH/RoHS) — noch nicht im Korpus."),
    ("creates_waste", "waste", "Abfall-/Entsorgungsrecht (u. a. WEEE) — noch nicht im Korpus."),
    ("consumes_energy_or_water", "energy_resources", "Energie-/Ökodesign-Recht — noch nicht im Korpus."),
]


def _unsupported_domains(profile: CanonicalProductRegulatoryProfile) -> List[UnsupportedDomain]:
    env = profile.environmental
    seen = set()
    out: List[UnsupportedDomain] = []
    for field, domain, note in _ENV_DOMAINS:
        if getattr(env, field) is True and domain not in seen:
            seen.add(domain)
            out.append(UnsupportedDomain(domain=domain, trigger=field, note=note))
    return out


def resolve_product_scope(profile: CanonicalProductRegulatoryProfile) -> ProductScopeResponse:
    nav = navigate(profile)

    if not nav.completeness_summary.ready_for_scope:
        return ProductScopeResponse(
            status=ScopeStatus.NEEDS_FACTS,
            completeness_summary=nav.completeness_summary,
            missing_facts=nav.missing_facts,
            suggested_questions=nav.suggested_questions,
        )

    scope = discover_scope(to_reasoning_profile(profile))  # exactly once
    result = RegulatoryScopeResult(
        applicable_regulations=scope.applicable_regulations,
        excluded_regulations=scope.excluded_regulations,
        uncertain_regulations=scope.uncertain_regulations,
        unsupported_domains=_unsupported_domains(profile),
        reasoning_summary=scope.reasoning_summary,
        confidence=scope.confidence,
    )
    return ProductScopeResponse(
        status=ScopeStatus.RESOLVED,
        completeness_summary=nav.completeness_summary,
        regulatory_scope=result,
    )
