"""
Tests pour la compatibilite --no-db.
"""

from dataclasses import dataclass
from pathlib import Path

from typer.testing import CliRunner

from pricewatch.app.cli import main as cli_main
from pricewatch.app.core.registry import get_registry
from pricewatch.app.core.schema import DebugInfo, DebugStatus, FetchMethod, ProductSnapshot
from pricewatch.app.db.connection import get_session, init_db, reset_engine
from pricewatch.app.db.models import Product
from pricewatch.app.stores.base import BaseStore


@dataclass
class FakeDbConfig:
    url: str


@dataclass
class FakeAppConfig:
    db: FakeDbConfig
    debug: bool = False
    enable_db: bool = True


class DummyStore(BaseStore):
    def __init__(self) -> None:
        super().__init__(store_id="dummy")

    def match(self, url: str) -> float:
        return 1.0 if "example.com" in url else 0.0

    def canonicalize(self, url: str) -> str:
        return url

    def extract_reference(self, url: str) -> str | None:
        return "REF-NODB"

    def parse(self, html: str, url: str) -> ProductSnapshot:
        return ProductSnapshot(
            source=self.store_id,
            url=url,
            title="Produit nodb",
            price=9.99,
            currency="EUR",
            reference="REF-NODB",
            debug=DebugInfo(method=FetchMethod.HTTP, status=DebugStatus.SUCCESS),
        )


class DummyFetchResult:
    def __init__(self, html: str) -> None:
        self.success = True
        self.html = html
        self.error = None


def test_cli_run_no_db(tmp_path, monkeypatch):
    """Le flag --no-db evite toute ecriture DB."""
    reset_engine()
    db_path = tmp_path / "nodb.db"
    config = FakeAppConfig(db=FakeDbConfig(url=f"sqlite:///{db_path}"))
    init_db(config)

    yaml_path = tmp_path / "config.yaml"
    out_path = tmp_path / "out.json"
    yaml_path.write_text(
        """
urls:
  - "https://example.com/product"
options:
  use_playwright: false
  save_html: false
  save_screenshot: false
""",
        encoding="utf-8",
    )

    registry = get_registry()
    previous_stores = list(registry._stores)
    registry._stores = []
    registry.register(DummyStore())

    monkeypatch.setattr(cli_main, "get_config", lambda: config)
    monkeypatch.setattr(cli_main, "setup_stores", lambda: None)
    monkeypatch.setattr(cli_main, "fetch_http", lambda url: DummyFetchResult("<html></html>"))

    runner = CliRunner()
    try:
        result = runner.invoke(
            cli_main.app,
            ["run", "--yaml", str(yaml_path), "--out", str(out_path), "--no-db"],
        )
    finally:
        registry._stores = previous_stores
        reset_engine()

    assert result.exit_code == 0
    assert out_path.exists()

    with get_session(config) as session:
        assert session.query(Product).count() == 0
