import json
from datetime import datetime, timezone
from pathlib import Path

from services.codebase_modularization_performance_service import (
    ROOT,
    _iter_python_files,
    build_codebase_inventory,
    write_codebase_inventory_receipt,
)


def test_inventory_generates_complete_prioritized_work_items():
    result = build_codebase_inventory(now=datetime(2026, 7, 11, tzinfo=timezone.utc))

    summary = result["summary"]
    assert summary["production_python_module_count"] > 0
    assert summary["large_python_module_count"] > 0
    assert summary["runtime_control_passed"] == summary["runtime_control_total"]
    assert summary["runtime_closure"] == "partial"
    assert 0 < summary["program_completion_percent"] < 100

    python_paths = {item["path"] for item in result["python_work_items"]}
    frontend_paths = {item["path"] for item in result["frontend_work_items"]}
    assert "services/pchome_mapping_backlog_service.py" in python_paths
    assert "routes/openclaw_bot_routes.py" in python_paths
    assert "templates/ai_intelligence.html" in frontend_paths
    assert all(item["work_item_id"] for item in result["python_work_items"])
    by_path = {item["path"]: item for item in result["python_work_items"]}
    assert by_path["routes/openclaw_bot_routes.py"]["status"] == "in_progress"
    assert by_path["services/pchome_mapping_backlog_service.py"]["status"] == "in_progress"
    assert summary["work_item_status_counts"]["in_progress"] == 4
    assert sum(summary["work_item_status_counts"].values()) == (
        summary["large_python_module_count"] + summary["large_frontend_asset_count"]
    )


def test_inventory_receipt_write_is_atomic_and_readable(tmp_path):
    result = build_codebase_inventory(now=datetime(2026, 7, 11, tzinfo=timezone.utc))
    target = tmp_path / "latest.json"

    written = write_codebase_inventory_receipt(result, path=target)

    assert written == target
    assert json.loads(target.read_text(encoding="utf-8"))["schema"] == result["schema"]
    assert not target.with_suffix(".json.tmp").exists()


def test_production_inventory_excludes_docker_build_ignored_sources():
    paths = {path.relative_to(ROOT).as_posix() for path in _iter_python_files(ROOT)}

    assert "data/__init__.py" not in paths
    assert "logs/__init__.py" not in paths
    assert not any(path.startswith(".claude/") for path in paths)


def test_scheduler_owns_daily_inventory_runtime():
    source = (Path(__file__).resolve().parents[1] / "run_scheduler.py").read_text(encoding="utf-8")

    assert 'day.at("04:15").do(run_codebase_modularization_performance_task)' in source
    assert '_save_stats("codebase_modularization_performance", payload)' in source


def test_scheduler_inventory_task_persists_completed_terminal_status(monkeypatch, tmp_path):
    import run_scheduler

    receipt_path = tmp_path / "latest.json"
    saved = []
    monkeypatch.setenv("CODEBASE_INVENTORY_RECEIPT_PATH", str(receipt_path))
    monkeypatch.setattr(
        run_scheduler,
        "_save_stats",
        lambda task_name, payload: saved.append((task_name, payload)),
    )

    result = run_scheduler.run_codebase_modularization_performance_task()

    assert result["status"] == "completed"
    assert result["receipt_path"] == str(receipt_path)
    assert saved == [("codebase_modularization_performance", result)]
    assert receipt_path.exists()
