from __future__ import annotations

import time

import pytest


async def _create_domain(client, slug="tododom"):
    r = await client.post("/domains/", json={"slug": slug, "name": "Todo Domain"})
    assert r.status_code == 201, r.text
    return r.json()


async def _create_repo(client, domain_slug, local_path, slug="todo-repo"):
    r = await client.post("/repos/", json={
        "slug": slug,
        "name": "Todo Repo",
        "domain_slug": domain_slug,
        "local_path": str(local_path),
        "remote_url": f"https://example.invalid/{slug}.git",
    })
    assert r.status_code == 201, r.text
    return r.json()


@pytest.mark.asyncio
async def test_todo_md_staleness_flags_unchanged_file(client, tmp_path):
    domain = await _create_domain(client)
    repo_root = tmp_path / "stale-repo"
    repo_root.mkdir()
    todo = repo_root / "TODO.md"
    todo.write_text("# TODO\n\n- [ ] item\n", encoding="utf-8")
    old = time.time() - (8 * 24 * 60 * 60)
    import os
    os.utime(todo, (old, old))

    await _create_repo(client, domain["slug"], repo_root, slug="stale-repo")

    r = await client.get("/repos/todo-md-staleness?stale_days=6")
    assert r.status_code == 200, r.text
    payload = r.json()
    assert payload["stale_count"] == 1
    assert payload["repos"][0]["repo_slug"] == "stale-repo"
    assert payload["repos"][0]["age_days"] >= 6


@pytest.mark.asyncio
async def test_todo_md_staleness_ignores_missing_and_fresh(client, tmp_path):
    domain = await _create_domain(client)

    fresh_root = tmp_path / "fresh-repo"
    fresh_root.mkdir()
    (fresh_root / "TODO.md").write_text("# TODO\n", encoding="utf-8")
    await _create_repo(client, domain["slug"], fresh_root, slug="fresh-repo")

    bare_root = tmp_path / "bare-repo"
    bare_root.mkdir()
    await _create_repo(client, domain["slug"], bare_root, slug="bare-repo")

    r = await client.get("/repos/todo-md-staleness?stale_days=6")
    assert r.status_code == 200, r.text
    payload = r.json()
    assert payload["stale_count"] == 0
    assert payload["total_with_todo"] == 1