"""Path helpers for Scholar Agent configuration and state."""

from __future__ import annotations

import os
from pathlib import Path
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from collections.abc import Mapping

APP_NAME = "scholar-agent"
_SCHOLAR_HOME_DIR = ".scholar"


def get_scholar_root() -> Path:
    """Return the project root by walking up from this file to find pyproject.toml."""
    candidate = Path(__file__).resolve().parent
    for _ in range(10):
        if (candidate / "pyproject.toml").exists():
            return candidate
        parent = candidate.parent
        if parent == candidate:
            break
        candidate = parent
    # Fallback for src layout: scholar_agent/config/ → parents[3] = repo root
    return Path(__file__).resolve().parents[3]


def _default_user_home() -> Path:
    """Cross-platform default: ~/scholar/ on all platforms.

    Simple, discoverable, consistent. Override with SCHOLAR_HOME env var.
    """
    return Path.home() / _SCHOLAR_HOME_DIR


def get_user_home(env: Mapping[str, str] | None = None) -> Path:
    env_map = os.environ if env is None else env
    override = env_map.get("SCHOLAR_HOME", "").strip()
    if override:
        return Path(override).expanduser().resolve()
    return _default_user_home().resolve()


def get_user_config_path(env: Mapping[str, str] | None = None) -> Path:
    return get_user_home(env) / "config" / "config.json"


def get_user_profile_path(profile: str, env: Mapping[str, str] | None = None) -> Path:
    return get_user_home(env) / "config" / "profiles" / f"{profile}.json"


def build_default_config(*, env: Mapping[str, str] | None = None, scholar_root: Path | None = None) -> dict:
    resolved_root = (scholar_root or get_scholar_root()).resolve()
    user_home = get_user_home(env)
    env_map = os.environ if env is None else env
    data_home = user_home if env_map.get("SCHOLAR_HOME", "").strip() else Path.home() / "scholar"
    profile = (env or os.environ).get("SCHOLAR_PROFILE", "default").strip() or "default"
    return {
        "knowledge_dir": str((data_home / "knowledge").resolve()),
        "index_path": str((user_home / "indexes" / "local" / "index.json").resolve()),
        "scholar_dir": str(resolved_root),
        "profile": profile,
        "paperpulse_url": "https://mindpulse.top",
        "paperpulse_token": "",
        "academic": {
            "paper_notes_dir": str((data_home / "paper-notes").resolve()),
            "daily_notes_dir": str((data_home / "daily-notes").resolve()),
            "search": {
                "sources": ["arxiv", "dblp", "semantic_scholar"],
                "default_conferences": [
                    "CVPR",
                    "ICCV",
                    "ECCV",
                    "ICLR",
                    "AAAI",
                    "NeurIPS",
                    "ICML",
                    "ACL",
                    "EMNLP",
                    "MICCAI",
                ],
                "max_results": 20,
                "date_range_days": 30,
            },
            "scoring": {
                "dimensions": ["relevance", "recency", "popularity", "quality"],
                "max_score": 3.0,
            },
            "research_interests": {
                "research_domains": {},
                "excluded_keywords": ["survey", "workshop"],
            },
            "precision_funnel": {
                "enabled": False,
                "max_daily_recommendations": 3,
                "hard_negative": {
                    "min_abstract_length": 500,
                    "reject_title_patterns": ["survey of", "review of", "tutorial on", "workshop on"],
                    "reject_abstract_starters": ["we present a survey", "this survey", "we review"],
                },
                "llm_review": {
                    "required_passes": [
                        "PROBLEM_DEFINED",
                        "METHOD_SPECIFIC",
                        "CONTRIBUTION_GENUINE",
                        "NO_RED_FLAGS",
                    ],
                    "call_delay_seconds": 1.0,
                    "max_survivors": 8,
                },
                "cross_comparison": {
                    "max_candidates": 8,
                },
            },
            "paper_db_path": "",
            "unified_pipeline": {
                "enabled": True,
                "max_daily_recommendations": 3,
                "arxiv_days": 7,
                "max_candidates": 15,
            },
        },
    }
