from __future__ import annotations

from datetime import datetime, timezone
from uuid import uuid4

from decode_content.contracts import (
    BUSINESS_STAGES,
    CREATION_STAGES,
    DIM_ATTRIBUTE_BY_TYPE,
    KNOWLEDGE_TYPES,
    SCOPE_TYPES,
    WHAT_KINDS,
    compute_contract_hash,
    iter_contract_artifacts,
    load_decode_contracts,
)
from decode_content.models import ContractSnapshot


def test_load_decode_contracts_covers_skill_prompts_and_cache():
    contract = load_decode_contracts()

    assert "判颗" in contract.phase1
    assert "作用域" in contract.phase2
    assert "payload" in contract.phase3.lower()
    assert contract.schema_for_particle_type("how")["$id"] == "ingest-payload-how.schema.json"
    assert any(src["relative_path"].startswith("prompts/") for src in contract.prompt_sources())
    assert contract.scope_tree_sources()
    assert len(contract.content_hash) == 64
    assert compute_contract_hash(contract) == contract.content_hash


def test_contract_constants_record_formal_business_terms():
    assert KNOWLEDGE_TYPES == ("how", "what", "why")
    assert BUSINESS_STAGES == ("灵感", "选题", "脚本", "视觉呈现", "拍摄表达")
    assert CREATION_STAGES == ("定向", "构思", "结构", "成文", "打磨")
    assert WHAT_KINDS == ("子集", "多维关系", "序列")
    assert SCOPE_TYPES == ("substance", "form", "feeling", "effect", "intent")
    assert DIM_ATTRIBUTE_BY_TYPE == {"how": "how", "what": "what", "why": "why"}


def test_contract_artifacts_can_feed_repository():
    snapshots = iter_contract_artifacts()

    assert snapshots[0].contract_name == "创作知识提取-skill"
    assert snapshots[0].contract_type == "skill"
    assert snapshots[0].content_hash and len(snapshots[0].content_hash) == 64
    assert snapshots[0].snapshot["constants"]["dim_attribute_by_type"]["how"] == "how"
    assert any(s.contract_type == "prompt_phase" for s in snapshots)
    assert any(s.contract_type == "schema" for s in snapshots)
    assert any(s.contract_type == "prompt" for s in snapshots)


def test_contract_snapshot_accepts_contract_artifact_timestamps():
    now = datetime.now(timezone.utc)

    snapshot = ContractSnapshot.model_validate(
        {
            "id": uuid4(),
            "contract_name": "创作知识提取-skill",
            "contract_type": "skill",
            "version_label": "test",
            "content_hash": "a" * 64,
            "source_path": "创作知识提取-skill",
            "snapshot": {},
            "created_at": now,
            "updated_at": now,
        }
    )

    assert snapshot.updated_at == now
