import json
from pathlib import Path

from fastapi import FastAPI
from fastapi.testclient import TestClient

from api.autotrain import autotrain_route


def test_autotrain_happy_path(tmp_path, monkeypatch):
    db_path = tmp_path / "autotrain.db"
    rules_path = tmp_path / "fashion_rules.json"
    rules_path.write_text(json.dumps({"roles": [], "role_max_items": {}}), encoding="utf-8")

    monkeypatch.setattr(autotrain_route, "DB_PATH", db_path)
    monkeypatch.setattr(autotrain_route, "TARGET_FILE_MAP", {"fashion_rules.json": rules_path})
    autotrain_route.init_db()

    app = FastAPI()
    app.include_router(autotrain_route.router)
    client = TestClient(app)

    feedback_payload = {
        "query": "tim ao khoac cho troi 35 do",
        "ai_response": "Minh goi y ao khoac ni nay rat am",
        "feedback_text": "Troi nong qua, AI con tu van ao khoac",
        "feedback_type": "bug",
    }

    submit_resp = client.post("/autotrain/feedback", json=feedback_payload)
    assert submit_resp.status_code == 200
    feedback_id = submit_resp.json()["feedback_id"]

    generate_resp = client.post(f"/autotrain/generate/{feedback_id}")
    assert generate_resp.status_code == 200
    rule_id = generate_resp.json()["rule_id"]

    validate_resp = client.get(f"/autotrain/rules/{rule_id}/validate")
    assert validate_resp.status_code == 200
    assert validate_resp.json()["ok"] is True

    approve_resp = client.post(f"/autotrain/rules/{rule_id}/approve")
    assert approve_resp.status_code == 200

    deploy_resp = client.post(f"/autotrain/rules/{rule_id}/deploy")
    assert deploy_resp.status_code == 200

    updated_rules = json.loads(rules_path.read_text(encoding="utf-8"))
    assert "auto_train_rules" in updated_rules
    assert updated_rules["auto_train_rules"][0]["rule_id"] == rule_id

    backup_files = list(Path(tmp_path).glob("fashion_rules.*.backup.json"))
    assert backup_files
