"""
dryft init: create .dryft/, context.md, intent.md, .gitignore, inject agent templates, save config.
"""

import os
from pathlib import Path
from typing import Literal

from .config import ensure_dryft_dir, save_config

DRYFT_DIR = ".dryft"
DRYFT_BLOCK_MARKER = "## Dryft Integration"


def _print_ghost_banner() -> None:
    o1 = "\x1b[38;5;202m"  # dark orange
    o2 = "\x1b[38;5;208m"  # orange
    o3 = "\x1b[38;5;214m"  # light orange
    y1 = "\x1b[38;5;220m"  # golden yellow
    y2 = "\x1b[38;5;226m"  # bright yellow
    y3 = "\x1b[38;5;228m"  # light yellow
    blk = "\x1b[38;5;0m"    # black
    r = "\x1b[0m"           # reset
    print(f"""
{o1}     ███████{r}
{o2}    █████████{r}
{o3}   ███████████{r}
{y1}   ███{blk}█{y1}███{blk}█{y1}███{r}
{y1}   ███████████{r}
{y2}   ████{blk}█{y2}████{r}
{y2}    ███████████{r}
{y3}      █ █ █ █{r}
""")


def _read_template(name: str) -> str:
    from importlib.resources import files
    raw = files("dryft").joinpath("templates", name).read_text(encoding="utf-8")
    return _strip_comment_first_line(raw).strip()


def _strip_comment_first_line(content: str) -> str:
    trimmed = content.lstrip()
    if trimmed.startswith("<!--") and "-->" in trimmed:
        after = trimmed[trimmed.index("-->") + 3 :].lstrip()
        return after
    return trimmed


def _inject_into_file(cwd: str, target_filename: str, block: str) -> Literal["injected", "skipped", "created"]:
    target = Path(cwd) / target_filename
    existing = ""
    try:
        existing = target.read_text(encoding="utf-8")
    except OSError:
        pass
    if DRYFT_BLOCK_MARKER in existing:
        return "skipped"
    new_content = f"{existing.rstrip()}\n\n{block}" if existing else block
    target.write_text(new_content, encoding="utf-8")
    return "injected" if existing else "created"


INITIAL_CONTEXT_MD = """# Dryft — Shared Development Context

> Not yet synced.
"""

INTENT_TEMPLATE = """# Intent

Agent-declared plan and active work. Update this file so the other developer's agent can avoid overlap.

**Agent:** Update the sections below when you start a task, when you change files, and when you finish a task.

## Current Task

(Describe what you're working on.)

## Planned Files

(Files you plan to modify next — one per line or bullet.)

## Dependencies

(Files or modules your work depends on.)

## Active Changes

(After modifying files: list functions/sections you changed.)

## Notes

(Optional.)
"""


def _get_default_developer_id() -> str:
    return (
        os.environ.get("DRYFT_DEVELOPER_ID")
        or os.environ.get("USER")
        or os.environ.get("USERNAME")
        or (os.getlogin() if hasattr(os, "getlogin") else "developer")
    )


def run_init(cwd: str) -> None:
    _print_ghost_banner()
    ensure_dryft_dir(cwd)
    base = Path(cwd) / DRYFT_DIR

    (base / "context.md").write_text(INITIAL_CONTEXT_MD, encoding="utf-8")
    (base / "intent.md").write_text(INTENT_TEMPLATE, encoding="utf-8")

    gitignore = Path(cwd) / ".gitignore"
    try:
        content = gitignore.read_text(encoding="utf-8")
        if ".dryft" not in content:
            addition = "\n.dryft/\n" if content.endswith("\n") else "\n.dryft/\n"
            gitignore.write_text(content + addition, encoding="utf-8")
    except FileNotFoundError:
        gitignore.write_text(".dryft/\n", encoding="utf-8")

    env_url = (os.environ.get("DRYFT_SERVER_URL") or "").strip()
    env_project = (os.environ.get("DRYFT_PROJECT_ID") or "").strip()
    env_ide = (os.environ.get("DRYFT_IDE") or "").strip().lower()
    default_ide = env_ide if env_ide in ("claude", "cursor", "both") else "both"
    default_dev = _get_default_developer_id()
    if env_url and env_project:
        server_url = env_url.rstrip("/")
        project_id = env_project
        developer_id = (os.environ.get("DRYFT_DEVELOPER_ID") or "").strip() or default_dev
    else:
        server_url = (
            input("Server URL (e.g. https://your-app.railway.app) [{}]: ".format(env_url)).strip() or env_url or ""
        ).rstrip("/")
        project_id = input("Project ID [{}]: ".format(env_project)).strip() or env_project or ""
        developer_id = (
            input("Your developer ID [{}]: ".format(default_dev)).strip() or default_dev
        )
    ide_answer = input("Which IDE are you using? (claude/cursor/both) [{}]: ".format(default_ide)).strip().lower() or default_ide
    ide = ide_answer if ide_answer in ("claude", "cursor", "both") else "both"

    if not server_url or not project_id:
        raise SystemExit("Server URL and Project ID are required. Re-run dryft config to set them.")

    config = {
        "server_url": server_url.rstrip("/"),
        "project_id": project_id,
        "developer_id": developer_id or _get_default_developer_id(),
        "poll_interval_ms": 5_000,
    }
    save_config(cwd, config)

    print("Dryft initialized in", base)

    if ide in ("claude", "both"):
        claude_block = _read_template("CLAUDE.md.dryft")
        claude_result = _inject_into_file(cwd, "CLAUDE.md", claude_block)
        if claude_result in ("injected", "created"):
            print("Dryft block added to CLAUDE.md")
        elif claude_result == "skipped":
            print("CLAUDE.md already contains Dryft integration (unchanged).")

    if ide in ("cursor", "both"):
        cursorrules_block = _read_template("cursorrules.dryft")
        cursor_result = _inject_into_file(cwd, ".cursorrules", cursorrules_block)
        if cursor_result in ("injected", "created"):
            print("Dryft block added to .cursorrules")
        elif cursor_result == "skipped":
            print(".cursorrules already contains Dryft integration (unchanged).")
